compressPlugin.js 2.59 KB
import CSSMinimizerWebpackPlugin from '../compiled/css-minimizer-webpack-plugin';

import TerserPlugin from '../compiled/terser-webpack-plugin';
import Config from '../compiled/webpack-5-chain';
const ESBuildCSSMinifyPlugin = require('../plugins/ESBuildCSSMinifyPlugin');
// eslint-disable-next-line import/extensions
const ParcelCSSMinifyPlugin = require('../plugins/ParcelCSSMinifyPlugin');
// eslint-disable-next-line import/extensions
const { CSSMinifier, Env, JSMinifier } = require('../types');

const { getEsBuildTarget } = require('../utils/getEsBuildTarget');

async function addCompressPlugin(opts) {
  const { config, userConfig, env } = opts;
  const jsMinifier = userConfig.jsMinifier || JSMinifier.esbuild;
  const cssMinifier = userConfig.cssMinifier || CSSMinifier.esbuild;

  if (
    env === Env.development ||
    process.env.COMPRESS === 'none' ||
    (jsMinifier === JSMinifier.none && cssMinifier === CSSMinifier.none)
  ) {
    config.optimization.minimize(false);
    return;
  }
  config.optimization.minimize(true);

  let minify: any;
  let terserOptions;
  if (jsMinifier === JSMinifier.esbuild) {
    minify = TerserPlugin.esbuildMinify;
    terserOptions = {
      target: getEsBuildTarget({
        targets: userConfig.targets || {},
      }),
    };
  } else if (jsMinifier === JSMinifier.terser) {
    minify = TerserPlugin.terserMinify;
  } else if (jsMinifier === JSMinifier.swc) {
    minify = TerserPlugin.swcMinify;
  } else if (jsMinifier === JSMinifier.uglifyJs) {
    minify = TerserPlugin.uglifyJsMinify;
  } else if (jsMinifier !== JSMinifier.none) {
    throw new Error(`Unsupported jsMinifier ${userConfig.jsMinifier}.`);
  }
  terserOptions = {
    ...terserOptions,
    ...userConfig.jsMinifierOptions,
  };
  if (jsMinifier !== JSMinifier.none) {
    config.optimization.minimizer(`js-${jsMinifier}`).use(TerserPlugin, [
      {
        minify,
        terserOptions,
      },
    ]);
  }

  if (cssMinifier === CSSMinifier.esbuild) {
    config.optimization.minimizer(`css-${cssMinifier}`).use(ESBuildCSSMinifyPlugin, [userConfig.cssMinifierOptions]);
  } else if (cssMinifier === CSSMinifier.cssnano) {
    config.optimization.minimizer(`css-${cssMinifier}`).use(CSSMinimizerWebpackPlugin, [
      {
        minimizerOptions: userConfig.cssMinifierOptions,
        parallel: true,
      },
    ]);
  } else if (cssMinifier === CSSMinifier.parcelCSS) {
    config.optimization.minimizer(`css-${cssMinifier}`).use(ParcelCSSMinifyPlugin);
  } else if (cssMinifier !== CSSMinifier.none) {
    throw new Error(`Unsupported cssMinifier ${userConfig.cssMinifier}.`);
  }
}

module.exports = addCompressPlugin;