Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. Its such a great tool for web development. One of the great feature it offers is the ability to tree shaking the javascript and CSS bundles with the right plugins.
For js tree shaking. I have used UglifyJsPlugin. Below is how I got the plugin works in my webpack.config.js file.
1 2 3 |
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), |
For css tree shaking. I have used PurifyCSSPlugin. Below is how I got the plugin works in my webpack.config.js file.
1 2 3 4 5 6 |
new PurifyCSSPlugin({ // Give paths to parse for rules. These should be absolute! paths: ['./ng2app/index.ejs'].concat(glob.sync('./ng2app/components/**/*.html')), // Will minify CSS code in addition to purify. minimize: true, }), |
In order for PurifyCSSPlugin, make sure the above code goes after ExtractTextPlugin. See below
1 2 3 4 5 6 7 8 9 10 11 12 |
new ExtractTextPlugin({ filename: "css/[name].bundle.css", disable: false, allChunks: true }), // Make sure this is after ExtractTextPlugin! new PurifyCSSPlugin({ // Give paths to parse for rules. These should be absolute! paths: ['./ng2app/index.ejs'].concat(glob.sync('./ng2app/components/**/*.html')), // Will minify CSS code in addition to purify. minimize: true, }), |
Another nice feature that I love to use in my webpack config is the ability to control how chunks should be sorted before they are included to the html via chunksSortMode option of html-webpack-plugin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
new HtmlWebpackPlugin({ title: 'My Dashboard (Webpack)', template: './index.ejs', hash: true, minify: { collapseWhitespace: true }, chunksSortMode: function (a, b) { //alphabetical order if (a.names[0] > b.names[0]) { return 1; } if (a.names[0] < b.names[0]) { return -1; } return 0; } }), |
To control the order of the chunks, I name them with the number at the front of that name. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
entry: { '1bootstrap': bootstrapEntryPoints.prod, '2core': [ './ng2app/polyfills.ts', './ng2app/vendor.ts' ], '3app': [ './ng2app/main.ts' ].concat(glob.sync('./ng2app/components/**/*.scss')) }, output: { path: outputPath, //publicPath: './', filename: 'js/[name].js', chunkFilename: 'js/[id].chunk.js' }, |
Any feedback, please leave your comments and I’ll get back to you ASAP.