score:45

Accepted answer

after observing number of viewers to this question i decided to conclude an answer from vikramaditya and sandeep.

to build the production code the first thing you have to create is production configuration with optimization packages like,

  new webpack.optimize.commonschunkplugin('common.js'),
  new webpack.optimize.dedupeplugin(),
  new webpack.optimize.uglifyjsplugin(),
  new webpack.optimize.aggressivemergingplugin()

then in the package.json file you can configure the build procedure with this production configuration

"scripts": {
    "build": "node_env=production webpack --config ./webpack.production.config.js"
},

now you have to run the following command to initiate the build

npm run build

as per my production build configuration webpack will build the source to ./dist directory.

now your ui code will be available in ./dist/ directory. configure your server to serve these files as static assets. done!

score:0

latest answer including webpack 5

for webpack (version not remember)

node_env=production webpack --config ./webpack.production.config.js

for webpack <4

plugins: [
    new webpack.defineplugin({
        'process.env':{
            'node_env': json.stringify('production')
                        //for development -> json.stringify('development')
        }
    })
]

for webpack >=4 (including webpack 5) - specify mode

 module.exports = {
   mode: 'production', //for development -> development
   devtool: 'inline-source-map',
   ...
 };

quote from webpack's official website

since webpack v4, specifying mode automatically configures defineplugin for you

score:3

if you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isprod to activate certain features only in certain situations and only have a single webpack.config.js file.

const isprod = (process.env.node_env === 'production');

 if (isprod) {
     plugins.push(new aotplugin({
      "mainpath": "main.ts",
      "hostreplacementpaths": {
        "environments/index.ts": "environments/index.prod.ts"
      },
      "exclude": [],
      "tsconfigpath": "src/tsconfig.app.json"
    }));
    plugins.push(new uglifyjsplugin({
      "mangle": {
        "screw_ie8": true
      },
      "compress": {
        "screw_ie8": true,
        "warnings": false
      },
      "sourcemap": false
    }));
  }

by the way: the dedupeplugin plugin was removed from webpack. you should remove it from your configuration.

update:

in addition to my previous answer:

if you want to hide your code for release, try enclosejs.com. it allows you to:

  • make a release version of your application without sources
  • create a self-extracting archive or installer
  • make a closed source gui application
  • put your assets inside the executable

you can install it with npm install -g enclose

score:5

in addition to gilson pj answer:

 new webpack.optimize.commonschunkplugin('common.js'),
 new webpack.optimize.dedupeplugin(),
 new webpack.optimize.uglifyjsplugin(),
 new webpack.optimize.aggressivemergingplugin()

with

"scripts": {
    "build": "node_env=production webpack -p --config ./webpack.production.config.js"
},

cause that the it tries to uglify your code twice. see https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.

you can fix this by removing the uglifyjsplugin from plugins-array or add the occurrenceorderplugin and remove the "-p"-flag. so one possible solution would be

 new webpack.optimize.commonschunkplugin('common.js'),
 new webpack.optimize.dedupeplugin(),
 new webpack.optimize.uglifyjsplugin(),
 new webpack.optimize.occurrenceorderplugin(),
 new webpack.optimize.aggressivemergingplugin()

and

"scripts": {
    "build": "node_env=production webpack --config ./webpack.production.config.js"
},

score:6

this will help you.

plugins: [
    new webpack.defineplugin({
      'process.env': {
        // this has effect on the react lib size
        'node_env': json.stringify('production'),
      }
    }),
    new extracttextplugin("bundle.css", {allchunks: false}),
    new webpack.optimize.aggressivemergingplugin(),
    new webpack.optimize.occurrenceorderplugin(),
    new webpack.optimize.dedupeplugin(),
    new webpack.optimize.uglifyjsplugin({
      mangle: true,
      compress: {
        warnings: false, // suppress uglification warnings
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        screw_ie8: true
      },
      output: {
        comments: false,
      },
      exclude: [/\.min\.js$/gi] // skip pre-minified libs
    }),
    new webpack.ignoreplugin(/^\.\/locale$/, [/moment$/]), //https://stackoverflow.com/questions/25384360/how-to-prevent-moment-js-from-loading-locales-with-webpack
    new compressionplugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minratio: 0
    })
  ],

score:9

you can use argv npm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -p flag "build": "webpack -p", you can add condition in webpack.config.js file like below

plugins: [
    new webpack.defineplugin({
        'process.env':{
            'node_env': argv.p ? json.stringify('production') : json.stringify('development')
        }
    })
]

and thats it.

score:26

just learning this myself. i will answer the second question:

  1. how to use these files? currently i am using webpack-dev-server to run the application.

instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:

var path = require("path");
var express = require("express");

var dist_dir = path.join(__dirname, "build");
var port = 3000;
var app = express();

//serving the files on the dist folder
app.use(express.static(dist_dir));

//send index.html when the user access the web
app.get("*", function (req, res) {
  res.sendfile(path.join(dist_dir, "index.html"));
});

app.listen(port);

then, in the package.json, add a script:

"start": "node server.js"

finally, run the app: npm run start to start the server

a detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (the example code is not compatible with the latest packages, but it will work with small tweaks)

score:42

use these plugins to optimize your production build:

  new webpack.optimize.commonschunkplugin('common'),
  new webpack.optimize.dedupeplugin(),
  new webpack.optimize.uglifyjsplugin(),
  new webpack.optimize.aggressivemergingplugin()

i recently came to know about compression-webpack-plugin which gzips your output bundle to reduce its size. add this as well in the above listed plugins list to further optimize your production code.

new compressionplugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minratio: 0.8
})

server side dynamic gzip compression is not recommended for serving static client-side files because of heavy cpu usage.

score:74

you can add the plugins as suggested by @vikramaditya. then to generate the production build. you have to run the the command

node_env=production webpack --config ./webpack.production.config.js

if using babel, you will also need to prefix babel_env=node to the above command.


Related Query

More Query from same tag