Sometimes we want to generate both compressed and uncompressed files at the same time. For example, when we build a lib package, we want the user to use the compressed code file as a CDN file. The simplest way to do this is by specifying an environment variable, such as MINIFY, as follows:


const path = require('path')

const isMinify = process.env.MINIFY

/** * @type {import('webpack').Configuration} */
const config = {
  entry: {

    index: './src/index.js'
  },
  output: {
    filename: isMinify ? '[name].min.js' : '[name].js'.path: path.join(__dirname, 'dist')},devtool: 'cheap-source-map'.optimization: {
    minimize: isMinify ? true : false}}module.exports = config

Copy the code

We can package different versions by specifying environment variables when we use them:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build:min": "MINIFY=1 webpack --config=webpack.config.js"."build": "webpack --config=webpack.config.js"
  }
Copy the code

The downside is that we need to run it twice.

The second method is to install the unminified-webpack-plugin which generates uncompressed files:


const path = require('path')
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

/** * @type {import('webpack').Configuration} */
const config = {
  entry: {
    index: './src/index.js',},output: {
    filename: '[name].min.js'.path: path.join(__dirname, 'dist')},devtool: 'cheap-source-map'.plugins: [
    new UnminifiedWebpackPlugin({})
  ]
}

module.exports = config

Copy the code

One drawback is that uncompressed files do not have sourcemap.

The third way is to specify multiple package entries and manually specify which files the compression plug-in (uglifyjs, Terser, etc.) should compress. For example, if we specify index.min.js, the file should be compressed as follows:


const path = require('path')
const TerserWebpackPlugin = require('terser-webpack-plugin');

/** * @type {import('webpack').Configuration} */
const config = {
  entry: {
    index: './src/index.js'.'index.min': './src/index.js'
  },
  output: {
    filename: '[name].js'.path: path.join(__dirname, 'dist')},devtool: 'cheap-source-map'.optimization: {
    minimize: true.minimizer: [
      new TerserWebpackPlugin({
        include: /min/.sourceMap: true}}})]module.exports = config

Copy the code

The key points are:

That’s when it’s perfect.

Finally, there is an advertisement. Recently, a new public account for sharing technology has been opened. You are welcome to follow 👇

This article was automatically published by ArtiPub