Skip to content

Instantly share code, notes, and snippets.

@byevhen2
Last active October 22, 2022 11:58
Show Gist options
  • Save byevhen2/5d285a4a80d5bef2b3da316c50d411e0 to your computer and use it in GitHub Desktop.
Save byevhen2/5d285a4a80d5bef2b3da316c50d411e0 to your computer and use it in GitHub Desktop.
How to build both minified and uncompressed bundle with Webpack

Q: How to build both minified and uncompressed bundle with Webpack?

A1: Use plugin UglifyJsPlugin (before webpack 4)

let webpack = require("webpack");

module.exports = {
    entry: {
        'bundle': './entry.js',
        'bundle.min': './entry.js'
    },
    output: {
        path: './dist',
        filename: '[name].js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            include: /\.min\.js$/,
            minimize: true
        })
    ]
};

Source: https://stackoverflow.com/a/34018909

A2: Use plugin UglifyJsPlugin (since webpack 4)

Install module uglifyjs-webpack-plugin:

$ npm install --save-dev uglifyjs-webpack-plugin

Then add the plugin to your webpack config:

let UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    optimization: {
        minimizer: [new UglifyJsPlugin()]
    }
};

Source: https://webpack.js.org/plugins/uglifyjs-webpack-plugin/

A3: Use plugin UnminifiedWebpackPlugin (probably since webpack 4)

Install module unminified-webpack-plugin:

$ npm install --save-dev unminified-webpack-plugin

Then add the plugin to your webpack config:

let UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        'bundle': './entry.js'
    },
    output: {
        path: './dist',
        filename: '[name].min.js'
    },
    plugins: [
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files bundle.min.js and bundle.js.

Sources:

A4: Make two builds simultaneously (any webpack version)

Use environment variable in your webpack config:

module.exports = {
    entry: {
        'bundle': './entry.js'
    },
    output: {
        path: './dist',
        filename: process.env.NODE_ENV === 'production' ? '[name].min.js' : '[name].js'
    }
};

Then make both builds:

$ webpack && cross-env NODE_ENV=production webpack -p
@ashclarke
Copy link

Thanks for this 👍🏻

@mwittmann
Copy link

Another cool way to do this is to give webpack an array of webpack configuration objects, as indicated here https://stackoverflow.com/a/55978987.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment