All files wpConfigs.js

79.41% Statements 54/68
62.12% Branches 41/66
72.72% Functions 16/22
78.12% Lines 50/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 4323x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                             3x     3x               12x                                                 3x           3x               24x                                 7x                         3x 13x   3x   3x   7x                                               3x                                 13x         13x 13x 104x 104x   13x                 13x                                                                                                       13x 13x                           13x             13x     13x                   13x                                                                             3x                         8x                                             8x 8x 8x     8x       8x     8x                                                       3x     5x                                                                                     3x                  
const fs = require('fs');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlReplaceWebpackPlugin = require('html-replace-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SvgToMiniDataURI = require('mini-svg-data-uri');
const TerserJSPlugin = require('terser-webpack-plugin');
const { babelLoaderResolve, babelPresetEnvResolve, cssLoaderResolve, tsLoaderResolve } = require('../lib/packages');
const { jsFileExtensions, OPTIONS, tsFileExtensions } = require('./global');
const { consoleMessage } = require('./logger');
const { setupWebpackDotenvFilesForEnv } = require('./dotenv');
 
/**
 * @module webpackConfigs
 */
 
/**
 * Assumption based preprocess loader for JS
 *
 * @param {object} dotenv
 * @param {string} dotenv._BUILD_SRC_DIR
 * @param {object} settings
 * @param {Array<string>} settings.jsFileExtensions
 * @returns {{module: {rules: Array}}}
 */
const preprocessLoaderJs = (
  { _BUILD_SRC_DIR: SRC_DIR = '' } = OPTIONS.dotenv || {},
  { jsFileExtensions: aliasJsFileExtensions = jsFileExtensions } = {}
) => ({
  module: {
    rules: [
      {
        test: new RegExp(`\\.(${aliasJsFileExtensions.join('|')})?$`),
        include: [SRC_DIR],
        resolve: {
          // Dependent on loader resolutions this may, or may not, be necessary
          extensions: aliasJsFileExtensions.map(ext => `.${ext}`)
        },
        use: [
          {
            loader: babelLoaderResolve,
            options: {
              presets: [babelPresetEnvResolve]
            }
          }
        ]
      }
    ]
  }
});
 
/**
 * Assumption based preprocess loader for Typescript
 *
 * @param {object} dotenv
 * @param {string} dotenv._BUILD_SRC_DIR
 * @param {object} settings
 * @param {Array<string>} settings.jsFileExtensions
 * @param {Array<string>} settings.tsFileExtensions
 * @returns {{module: {rules: Array}}}
 */
const preprocessLoaderTs = (
  { _BUILD_SRC_DIR: SRC_DIR = '' } = OPTIONS.dotenv || {},
  {
    jsFileExtensions: aliasJsFileExtensions = jsFileExtensions,
    tsFileExtensions: aliasTsFileExtensions = tsFileExtensions
  } = {}
) => ({
  module: {
    rules: [
      {
        test: new RegExp(`\\.(${[...aliasTsFileExtensions, ...aliasJsFileExtensions].join('|')})?$`),
        include: [SRC_DIR],
        resolve: {
          // Dependent on loader resolutions this may, or may not, be necessary
          extensions: [...aliasTsFileExtensions, ...aliasJsFileExtensions].map(ext => `.${ext}`)
        },
        use: [
          {
            loader: tsLoaderResolve
          }
        ]
      }
    ]
  }
});
 
/**
 * Assumption based preprocess loader for none
 *
 * @returns {{module: {rules: Array}}}
 */
const preprocessLoaderNone = () => ({
  module: {
    rules: []
  }
});
 
/**
 * Assumption based preprocess loader
 *
 * @param {object} options
 * @param {string} options.loader
 * @returns {{module: {rules: Array}}}
 */
const preprocessLoader = ({ loader } = OPTIONS) => {
  switch (loader) {
    case 'js':
      return preprocessLoaderJs();
    case 'ts':
      return preprocessLoaderTs();
    default:
      return preprocessLoaderNone();
  }
};
 
/**
 * Common webpack settings between environments.
 *
 * @param {object} dotenv
 * @param {string} dotenv._BUILD_APP_INDEX_PREFIX
 * @param {string} dotenv._BUILD_DIST_DIR
 * @param {string} dotenv._BUILD_HTML_INDEX_DIR
 * @param {string} dotenv._BUILD_PUBLIC_PATH
 * @param {string} dotenv._BUILD_RELATIVE_DIRNAME
 * @param {string} dotenv._BUILD_SRC_DIR
 * @param {string} dotenv._BUILD_STATIC_DIR
 * @param {string} dotenv._BUILD_UI_NAME
 * @param {object} settings
 * @param {object} settings.consoleMessage
 * @param {Array<string>} settings.jsFileExtensions
 * @param {Function} settings.setupWebpackDotenvFilesForEnv
 * @param {Array<string>} settings.tsFileExtensions
 * @returns {{output: {path: string, filename: string, publicPath: string, clean: boolean}, entry: {app: string},
 *     resolve: {cacheWithContext: boolean, symlinks: boolean}, plugins: any[], module: {rules: Array}}}
 */
const common = (
  {
    _BUILD_APP_INDEX_PREFIX: APP_INDEX_PREFIX,
    _BUILD_DIST_DIR: DIST_DIR,
    _BUILD_HTML_INDEX_DIR: HTML_INDEX_DIR = '',
    _BUILD_PUBLIC_PATH: PUBLIC_PATH,
    _BUILD_RELATIVE_DIRNAME: RELATIVE_DIRNAME,
    _BUILD_SRC_DIR: SRC_DIR = '',
    _BUILD_STATIC_DIR: STATIC_DIR = '',
    _BUILD_UI_NAME: UI_NAME
  } = OPTIONS.dotenv || {},
  {
    consoleMessage: aliasConsoleMessage = consoleMessage,
    jsFileExtensions: aliasJsFileExtensions = jsFileExtensions,
    setupWebpackDotenvFilesForEnv: aliasSetupWebpackDotenvFilesForEnv = setupWebpackDotenvFilesForEnv,
    tsFileExtensions: aliasTsFileExtensions = tsFileExtensions
  } = {}
) => ({
  context: RELATIVE_DIRNAME,
  entry: {
    app: (() => {
      let entryFiles;
      try {
        const fileExtensions = [...aliasTsFileExtensions, ...aliasJsFileExtensions];
        const entryFilesSet = new Set([...fileExtensions.map(ext => path.join(SRC_DIR, `${APP_INDEX_PREFIX}.${ext}`))]);
        entryFiles = Array.from(entryFilesSet).filter(file => fs.existsSync(file));
 
        Iif (!entryFiles.length) {
          aliasConsoleMessage.warn(
            `webpack app entry file error: Missing entry/app file. Expected an index file! ${APP_INDEX_PREFIX}.(${fileExtensions.join('|')})`
          );
        }
      } catch (e) {
        aliasConsoleMessage.error(`webpack app entry file error: ${e.message}`);
      }
 
      return entryFiles;
    })()
  },
  output: {
    filename: '[name].bundle.js',
    path: DIST_DIR,
    publicPath: PUBLIC_PATH,
    clean: true
  },
  module: {
    rules: [
      {
        test: /\.(svg|ttf|eot|woff|woff2)$/,
        include: input => input.indexOf('fonts') > -1 || input.indexOf('icon') > -1,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[hash][ext][query]'
        }
      },
      {
        test: /\.svg$/i,
        include: input => input.indexOf('fonts') === -1 || input.indexOf('icon') === -1,
        type: 'asset',
        parser: {
          dataUrlCondition: { maxSize: 5000 }
        },
        generator: {
          dataUrl: content => SvgToMiniDataURI(content.toString()),
          filename: 'images/[hash][ext][query]'
        }
      },
      {
        test: /\.(jpg|jpeg|png|gif)$/i,
        type: 'asset',
        parser: {
          dataUrlCondition: { maxSize: 5000 }
        },
        generator: {
          filename: 'images/[hash][ext][query]'
        }
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, cssLoaderResolve]
      }
    ]
  },
  plugins: [
    ...aliasSetupWebpackDotenvFilesForEnv({
      directory: RELATIVE_DIRNAME
    }),
    ...(() => {
      const staticFile = path.join(HTML_INDEX_DIR, 'index.html');
      Iif (fs.existsSync(staticFile)) {
        return [
          new HtmlWebpackPlugin({
            ...(UI_NAME && { title: UI_NAME }),
            template: staticFile
          }),
          new HtmlReplaceWebpackPlugin([
            {
              pattern: /%([A-Z_]+)%/g,
              replacement: (match, $1) => process.env?.[$1] || match
            }
          ])
        ];
      }
      return [
        new HtmlWebpackPlugin({
          ...(UI_NAME && { title: UI_NAME })
        })
      ];
    })(),
    ...(() => {
      try {
        let fileResults;
 
        Iif (fs.existsSync(STATIC_DIR)) {
          fileResults = fs
            .readdirSync(STATIC_DIR)
            ?.filter(fileDir => !/^(\.|index)/.test(fileDir))
            ?.map(fileDir => ({
              from: path.join(STATIC_DIR, fileDir),
              to: path.join(DIST_DIR, fileDir)
            }));
        }
 
        return (
          (fileResults?.length > 0 && [
            new CopyPlugin({
              patterns: fileResults
            })
          ]) ||
          []
        );
      } catch (e) {
        aliasConsoleMessage.error(`webpack.common.js copy plugin error: ${e.message}`);
        return [];
      }
    })()
  ],
  resolve: {
    symlinks: false,
    cacheWithContext: false
  }
});
 
/**
 * Development webpack configuration.
 *
 * @param {object} dotenv
 * @param {string} dotenv.NODE_ENV
 * @param {string} dotenv._BUILD_DIST_DIR
 * @param {string} dotenv._BUILD_HOST
 * @param {string} dotenv._BUILD_HTML_INDEX_DIR
 * @param {string} dotenv._BUILD_OPEN_PATH
 * @param {string} dotenv._BUILD_RELATIVE_DIRNAME
 * @param {string} dotenv._BUILD_PORT
 * @param {string} dotenv._BUILD_SRC_DIR
 * @param {string} dotenv._BUILD_STATIC_DIR
 * @param {object} settings
 * @param {Function} settings.setupWebpackDotenvFilesForEnv
 * @returns {{mode: string, devtool: string, devServer: {historyApiFallback: boolean, static: {directory: string},
 *     port: string, compress: boolean, host: string, devMiddleware: {writeToDisk: boolean, stats: string|object},
 *     client: {overlay: boolean, progress: boolean}, hot: boolean, watchFiles: {paths: string[]}}, plugins: any[]}}
 */
const development = (
  {
    NODE_ENV: MODE,
    _BUILD_DIST_DIR: DIST_DIR,
    _BUILD_HOST: HOST,
    _BUILD_HTML_INDEX_DIR: HTML_INDEX_DIR,
    _BUILD_OPEN_PATH: OPEN_PATH,
    _BUILD_RELATIVE_DIRNAME: RELATIVE_DIRNAME,
    _BUILD_PORT: PORT,
    _BUILD_SRC_DIR: SRC_DIR,
    _BUILD_STATIC_DIR: STATIC_DIR
  } = OPTIONS.dotenv || {},
  { setupWebpackDotenvFilesForEnv: aliasSetupWebpackDotenvFilesForEnv = setupWebpackDotenvFilesForEnv } = {}
) => ({
  mode: MODE,
  devtool: 'eval-source-map',
  devServer: {
    ...((OPEN_PATH && { open: OPEN_PATH }) || {}),
    host: HOST,
    port: PORT,
    compress: true,
    historyApiFallback: true,
    hot: true,
    devMiddleware: {
      stats: 'errors-warnings',
      writeToDisk: false
    },
    client: {
      overlay: false,
      progress: true
    },
    static: {
      directory: DIST_DIR
    },
    watchFiles: {
      paths: (() => {
        const updatedPaths = new Set();
        Eif (SRC_DIR) {
          updatedPaths.add(path.basename(SRC_DIR));
        }
 
        Iif (HTML_INDEX_DIR) {
          updatedPaths.add(path.basename(HTML_INDEX_DIR));
        }
 
        Iif (STATIC_DIR) {
          updatedPaths.add(path.basename(STATIC_DIR));
        }
        return Array.from(updatedPaths).map(value => path.join(value, '**', '*'));
      })()
    }
  },
  plugins: [
    ...aliasSetupWebpackDotenvFilesForEnv({
      directory: RELATIVE_DIRNAME,
      env: MODE
    }),
    new MiniCssExtractPlugin({
      filename: '[name].bundle.css'
    })
  ]
});
 
/**
 * Production webpack configuration.
 *
 * @param {object} dotenv
 * @param {string} dotenv.NODE_ENV
 * @param {string} dotenv._BUILD_RELATIVE_DIRNAME
 * @param {object} settings
 * @param {Function} settings.setupWebpackDotenvFilesForEnv
 * @returns {{mode: string, devtool: undefined, output: {chunkFilename: string, filename: string},
 *     optimization: {minimize: boolean, runtimeChunk: string, minimizer: Array<any|CssMinimizerPlugin>,
 *     splitChunks: {chunks: string, cacheGroups: {vendor: {test: RegExp, chunks: string, name: string}}}},
 *     plugins: Array}}
 */
const production = (
  { NODE_ENV: MODE, _BUILD_RELATIVE_DIRNAME: RELATIVE_DIRNAME } = OPTIONS.dotenv || {},
  { setupWebpackDotenvFilesForEnv: aliasSetupWebpackDotenvFilesForEnv = setupWebpackDotenvFilesForEnv } = {}
) => ({
  mode: MODE,
  devtool: undefined,
  output: {
    chunkFilename: '[name].[contenthash:8].chunk.js',
    filename: '[name].[contenthash:8].js'
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserJSPlugin({
        parallel: true
      }),
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: ['default', { mergeLonghand: false }]
        }
      })
    ],
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          chunks: 'all',
          name: 'vendor',
          test: /[\\/]node_modules[\\/]/
        }
      }
    }
  },
  plugins: [
    ...aliasSetupWebpackDotenvFilesForEnv({
      directory: RELATIVE_DIRNAME,
      env: MODE
    }),
    new MiniCssExtractPlugin({
      chunkFilename: '[name].[contenthash:8].chunk.css',
      filename: '[name].[contenthash:8].css'
    })
  ]
});
 
module.exports = {
  common,
  development,
  preprocessLoader,
  preprocessLoaderNone,
  preprocessLoaderJs,
  preprocessLoaderTs,
  production
};