269

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

0

14 Answers 14

169

webpack.config.js:

const webpack = require("webpack");

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

Since Webpack 4, webpack.optimize.UglifyJsPlugin has been deprecated and its use results in error:

webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead

As the manual explains, the plugin can be replaced with minimize option. Custom configuration can be provided to the plugin by specifying UglifyJsPlugin instance:

const webpack = require("webpack");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  // ...
  optimization: {
    minimize: true,
    minimizer: [new UglifyJsPlugin({
      include: /\.min\.js$/
    })]
  }
};

This does the job for a simple setup. A more effective solution is to use Gulp together with Webpack and do the same thing in one pass.

3
  • 1
    @FeloVilches I don't even mention that this is done in webpack.config.js, but this is presumed once we are in Node.js land and use Webpack. Sep 13, 2017 at 5:50
  • 3
    Hmm, in webpack 4 i got: Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.
    – entithat
    Apr 10, 2018 at 14:03
  • 7
    Update: now you can use terser-webpack-plugin webpack.js.org/plugins/terser-webpack-plugin
    – ijse
    Jan 22, 2019 at 7:56
168

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.

8
  • 6
    Node has one "default" variable for that, it's called NODE_ENV. Feb 15, 2016 at 23:11
  • 3
    Isn't the option called compress instead of minimize? Mar 31, 2016 at 13:46
  • 1
    Just a small gotcha: when you call webpack with arguments, like webpack -p the settings from webpack.optimize.UglifyJsPlugin in your webpack config will be (at least partially) ignored (at least setting mangle: false is ignored). May 9, 2016 at 23:46
  • 2
    Notice that this generates only one file at a time. So in order to make this work for the question there should be multiple Webpack passes, webpack && webpack -p. Feb 23, 2017 at 13:13
  • 1
    For anyone reading this, I would suggest using definePlugin instead, which I think is installed by default with Webpack.
    – Ben Gubler
    Aug 29, 2018 at 22:18
57

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

3
  • 2
    Seems very simple solution to me; just that as of webpack v3.5.5 it has built-in switch called --optimize-minimize or -p.
    – synergetic
    Sep 3, 2017 at 2:02
  • 1
    The idea is cool, but not work now, webpack will yell "Unknown argument: minimize" Solution: use --env.minimize more details in the following link github.com/webpack/webpack/issues/2254
    – Zhli
    Dec 21, 2017 at 10:41
  • Can use more standard way to pass environment indication in webpack: stackoverflow.com/questions/44113359/…
    – MaMazav
    Jan 8, 2018 at 20:20
41

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.

1
  • Thanks @everett1992 , this solution works great. The vast majority of the time I run the dev build, then when I'm done I use the -p flag to spit out a minified production build. No need to create two separate Webpack configs!
    – pmont
    Dec 11, 2016 at 7:01
37

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!^^

4
  • This plugin seems to not be compatible with SourceMapDevToolPlugin. Any suggestions to retain source maps?
    – BhavikUp
    Oct 11, 2016 at 5:58
  • @BhavikUp, it's not supported. Do you think you really need source map to be output along with the final js file?
    – Howard
    Oct 14, 2016 at 2:50
  • 1
    "No need to execute webpack twice [...]" Nice, but estus's solution also does not require to "execute webpack twice" and additionally does not require adding a third-party plugin.
    – Louis
    Nov 4, 2016 at 12:57
  • @Howard Man, you're right on time :). At least, for me. Thanks a lot for the great plug-in! Seems to work perfectly with webpack 2 and -p option.
    – gaperton
    May 1, 2017 at 20:43
36

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.

1
  • yes this is an easy solution that allows you to build only once
    – Flion
    Aug 1, 2016 at 8:55
16

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

1
  • 3
    Thanks, this works great, but it sure would be nice if there was a better way to do this than to maintain two config files given that this is such a common use case (just about any library build). Oct 10, 2017 at 21:03
12

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.

3
  • Thanks for your helpful answer on an aged-but-somehow-still-relevant question, Mauro ^_^
    – Mulan
    Jan 30, 2017 at 11:58
  • 1
    Can't find option minimize in docs. Perhaps it's deprecated?
    – adi518
    Mar 30, 2017 at 10:31
  • @adi518 Maybe you are using a newer version of the plugin and not the one, bundled within webpack?
    – thexpand
    Mar 7, 2018 at 8:23
9

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.

4

webpack entry.jsx ./output.js -p

works for me, with -p flag.

0
4

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.

3

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
1
  • I got this error ERROR in unknown: Invalid typeof value May 9, 2018 at 13:09
3

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'),
];
0

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.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.