/* eslint-disable import/no-extraneous-dependencies */

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

const commonPaths = require('./paths');

module.exports = {
  output: {
    publicPath: commonPaths.publicPath,
    filename: `${commonPaths.scriptsPath}/${commonPaths.jsFolder}/[name].[hash].js`,
    path: commonPaths.outputPath,
    chunkFilename: `${commonPaths.scriptsPath}/${commonPaths.jsFolder}/[name].[chunkHash].js`,
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/, // allows both .jsx and .js
        exclude: /node_modules/,
        include: commonPaths.source,
        use: [
          {
            loader: 'babel-loader',
          },
        ],
      },
      {
        test: /\.(sa|sc|c)ss$/,
        enforce: 'pre',
        use: [{
          loader: MiniCssExtractPlugin.loader,
        },
        {
          loader: 'css-loader',
          options: {
            modules: false,
          },
        },
        {
          loader: 'sass-loader',
        },
        ],
      },
    ],
  },
  optimization: {
    usedExports: true, // to remove unused exports
    splitChunks: {
      chunks: 'all',
      automaticNameDelimiter: '.',
      minSize: 30000,
    },
    noEmitOnErrors: true,
    minimize: true,
    minimizer: [
      new TerserPlugin({
        parallel: true, // use multi-process parallel running to improve the build speed
        sourceMap: false, // set to true if you want JS source maps
        terserOptions: {
          mangle: true, // pass false to skip mangling names
          toplevel: false, // set to true if you wish to enable top level variable and function name mangling and to drop unused variables and functions
          ie8: false, // set to true to support IE8.
          keep_fnames: false, // pass true to prevent discarding or mangling of function names
          output: {
            comments: false,
          },
        },
      }),
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.css$/g,
        cssProcessorPluginOptions: {
          preset: [
            'default',
            {
              discardComments: {
                removeAll: true,
              },
            },
          ],
        },
        canPrint: true,
      }),
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: `${commonPaths.assetPath}/${commonPaths.cssFolder}/[name].css`,
      chunkFilename: '[id].css',
    }),
    new BundleAnalyzerPlugin({
      generateStatsFile: true,
      reportFilename: 'bundleReport.html',
      analyzerMode: 'static',
    }),
  ],
};
