[javascript] How to build minified and uncompressed bundle with webpack?

Here's my webpack.config.js

var webpack = require("webpack");

module.exports = {

  entry: "./entry.js",
  devtool: "source-map",
  output: {
    path: "./dist",
    filename: "bundle.min.js"
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({minimize: true})
  ]
};

I'm building with

$ webpack

In my dist folder, I'm only getting

  • bundle.min.js
  • bundle.min.js.map

I'd also like to see the uncompressed bundle.js

This question is related to javascript node.js webpack

The answer is


In my opinion it's a lot easier just to use the UglifyJS tool directly:

  1. npm install --save-dev uglify-js
  2. Use webpack as normal, e.g. building a ./dst/bundle.js file.
  3. Add a build command to your package.json:

    "scripts": {
        "build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
    }
    
  4. Whenever you want to build a your bundle as well as uglified code and sourcemaps, run the npm run build command.

No need to install uglify-js globally, just install it locally for the project.


You can run webpack twice with different arguments:

$ webpack --minimize

then check command line arguments in webpack.config.js:

var path = require('path'),
  webpack = require('webpack'),
  minimize = process.argv.indexOf('--minimize') !== -1,
  plugins = [];

if (minimize) {
  plugins.push(new webpack.optimize.UglifyJsPlugin());
}

...

example webpack.config.js


According with this line: https://github.com/pingyuanChen/webpack-uglify-js-plugin/blob/master/index.js#L117

should be something like:

var webpack = require("webpack");

module.exports = {

  entry: "./entry.js",
  devtool: "source-map",
  output: {
    path: "./dist",
    filename: "bundle.js"
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
     minimize: true,
     compress: false
    })
  ]
};

Indeed you can have multiple builds by exporting different configs according your env / argv strategies.


You can format your webpack.config.js like this:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./entry.js",
    output: {
        path: __dirname + "/dist",
        filename: "library.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};'

And then to build it unminified run (while in the project's main directory):

$ webpack

To build it minified run:

$ NODE_ENV=production webpack

Notes: Make sure that for the unminified version you change the output file name to library.js and for the minified library.min.js so they do not overwrite each other.


You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:

const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');

const PROD = JSON.parse(process.env.PROD_ENV || '0');

module.exports = {

  entry: './entry.js',
  devtool: 'source-map',
  output: {
    path: './dist',
    filename: PROD ? 'bundle.min.js' : 'bundle.js'
  },
  optimization: {
    minimize: PROD,
    minimizer: [
      new TerserPlugin({ parallel: true })
  ]
};

and then just set this variable when you want to minify it:

$ PROD_ENV=1 webpack

Edit:

As mentioned in the comments, NODE_ENV is generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set const PROD = (process.env.NODE_ENV === 'production'), and continue normally.


You can define two entry points in your webpack configuration, one for your normal js and the other one for minified js. Then you should output your bundle with its name, and configure UglifyJS plugin to include min.js files. See the example webpack configuration for more details:

module.exports = {
 entry: {
   'bundle': './src/index.js',
   'bundle.min': './src/index.js',
 },

 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: "[name].js"
 },

 plugins: [
   new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
   })
 ]
};

After running webpack, you will get bundle.js and bundle.min.js in your dist folder, no need for extra plugin.


To add another answer, the flag -p (short for --optimize-minimize) will enable the UglifyJS with default arguments.

You won't get a minified and raw bundle out of a single run or generate differently named bundles so the -p flag may not meet your use case.

Conversely the -d option is short for --debug --devtool sourcemap --output-pathinfo

My webpack.config.js omits devtool, debug, pathinfo, and the minmize plugin in favor of these two flags.


webpack entry.jsx ./output.js -p

works for me, with -p flag.


You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.

Installation

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

Usage

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

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^


You can create two configs for webpack, one that minifies the code and one that doesn't (just remove the optimize.UglifyJSPlugin line) and then run both configurations at the same time $ webpack && webpack --config webpack.config.min.js


I found a new solution for this problem.

This uses an array of configuration to enable webpack to build the minified and non-minified version in parallel. This make build faster. No need to run the webpack twice. No need extra plugins. Just webpack.

webpack.config.js

const devConfig = {
  mode: 'development',
  entry: { bundle: './src/entry.js' },
  output: { filename: '[name].js' },
  module: { ... },
  resolve: { ... },
  plugins: { ... }
};

const prodConfig = {
  ...devConfig,
  mode: 'production',
  output: { filename: '[name].min.js' }
};

module.exports = (env) => {
  switch (env) {
    case 'production':
      return [devConfig, prodConfig];
    default:
      return devConfig;
  }
};

Running webpack will only build the non-minified version.

Running webpack --env=production will build the minified and non-minified version at the same time.


I had the same issue, and had to satisfy all these requirements:

  • Minified + Non minified version (as in the question)
  • ES6
  • Cross platform (Windows + Linux).

I finally solved it as follows:

webpack.config.js:

const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");

module.exports = getConfiguration;

function getConfiguration(env) {
    var outFile;
    var plugins = [];
    if (env === 'prod') {
        outFile = 'mylib.dev';
        plugins.push(new MinifyPlugin());
    } else {
        if (env !== 'dev') {
            console.log('Unknown env ' + env + '. Defaults to dev');
        }
        outFile = 'mylib.dev.debug';
    }

    var entry = {};
    entry[outFile] = './src/mylib-entry.js';

    return {
        entry: entry,
        plugins: plugins,
        output: {
            filename: '[name].js',
            path: __dirname
        }
    };
}

package.json:

{
    "name": "mylib.js",
    ...
    "scripts": {
        "build": "npm-run-all webpack-prod webpack-dev",
        "webpack-prod": "npx webpack --env=prod",
        "webpack-dev": "npx webpack --env=dev"
    },
    "devDependencies": {
        ...
        "babel-minify-webpack-plugin": "^0.2.0",
        "npm-run-all": "^4.1.2",
        "webpack": "^3.10.0"
    }
}

Then I can build by (Don't forget to npm install before):

npm run-script build

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to webpack

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 Support for the experimental syntax 'classProperties' isn't currently enabled npx command not found where is create-react-app webpack config and files? How can I go back/route-back on vue-router? webpack: Module not found: Error: Can't resolve (with relative path) Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' The create-react-app imports restriction outside of src directory How to import image (.svg, .png ) in a React Component How to include css files in Vue 2