How to minimize the size of webpack's bundle?

后端 未结 5 1499
心在旅途
心在旅途 2020-11-30 18:47

I\'m writing a web app using react and webpack as my module bundler. My jsx code is really light so far, the size of the entire folder

5条回答
  •  甜味超标
    2020-11-30 19:04

    01/2017 EDIT - I've since learned a little more about different Webpack Plugins, and wanted to update this. It turns out that UglifyJS has a littany of config options that don't seem to be very mainstream, but can have a dramatic effect on your bundle size. This is my current config w/ some annotations (docs on site are great):

     new webpack.optimize.UglifyJsPlugin({
          comments: false, // remove comments
          compress: {
            unused: true,
            dead_code: true, // big one--strip code that will never execute
            warnings: false, // good for prod apps so users can't peek behind curtain
            drop_debugger: true,
            conditionals: true,
            evaluate: true,
            drop_console: true, // strips console statements
            sequences: true,
            booleans: true,
          }
        })
    

    I once encountered an obscure problem with uglify-ication of escaped unicode chars, so be mindful if you employ these transformations that edge-case things like that are possible.

    You can read more about the specific options webpack supports in the webpack docs w/ some follow-on links to further reading.


    (sidenote: I think your package.json is mixed-up... at least a few of those dev-dependencies are dependencies in every package.json I've seen (e.g., the react-starter-kit)

    If you're preparing for production, there are a few more steps you should take to get your file size down. Here's a snip of my webpack.config.js:

     plugins: [
    
    
            new webpack.optimize.UglifyJsPlugin(),
            new webpack.optimize.DedupePlugin(),
            new webpack.DefinePlugin({
                'process.env': {
                    'NODE_ENV': JSON.stringify('production')
                }
            })
        ],
    

    1) minifies/uglifies your code

    2) replaces duplicate code to minimize file-size

    3) tells webpack to omit some things it uses for node environment builds

    Finally, if you use a source map (which you probably should), you'll want to add the appropriate line. Sentry wrote a nice blog post about this.

    In my build, i use devtool: 'source-map' for production

提交回复
热议问题