Search code examples
javascriptnpmecmascript-6webpack-2

Minimize bundle with webpack2


Is it possible to minimize my bundle file and all of the used modules. I use import in javascript but I want webpack to minimize all the imported js files as well. This means removing all unused code from the imported external libraries. Is this possible. Especially plotly is a really large librarie but I use pie charts only. I don't think my bundle needs all of the code from plotly. Here is my webpack configuration file:

const path              = require('path');
const webpack           = require('webpack');
const UglifyJSPlugin    = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const config = {
    entry: 
    {
        cash: './js/page/cash.js'
    },
    output: 
    {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, 'dist')
    },
    resolve: 
    {
        modules: [
            path.resolve(__dirname, 'js')
        ],
        alias : {
            knockout: path.resolve(__dirname, 'js/knockout-3.4.2.js'),
            moment: path.resolve(__dirname,'js/moment.js')
        }
    },
    module: 
    {
        rules: [
            {
                test: /\.js$/, 
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        new webpack.LoaderOptionsPlugin({
            minimize: true
        }),
        new UglifyJSPlugin({ 
            comments: false,
            sourceMap: false,
            compress: {
                unused: true,
                dead_code: true,
                warnings: false,
                drop_debugger: true,
                conditionals: true,
                evaluate: true,
                drop_console: true,
                sequences: true,
                booleans: true
            },
            mangle: true
        }),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.OccurrenceOrderPlugin()
    ]
};

module.exports = config;

Solution

  • The best way to do this is to selectively import the members (functions) you require with ES6 import syntax. Webpack's documentation describes how. If you do that, Webpack should do the Tree Shaking automagically.