How to minimize the size of webpack's bundle?

后端 未结 5 1484
心在旅途
心在旅途 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:00

    According to your comments you are using material-ui and react-bootstrap. Those dependencies are bundled by webpack along with your react and react-dom packages. Any time you require or import a package it is bundled as part of your bundle file.

    And here it comes my guess. You are probably importing the react-bootstrap and material-ui components using the library way:

    import { Button } from 'react-bootstrap';
    import { FlatButton } from 'material-ui';
    

    This is nice and handy but it does not only bundles Button and FlatButton (and their dependencies) but the whole libraries.

    One way to alleviate it is to try to only import or require what is needed, lets say the component way. Using the same example:

    import Button from 'react-bootstrap/lib/Button';
    import FlatButton from 'material-ui/lib/flat-button';
    

    This will only bundle Button, FlatButton and their respective dependencies. But not the whole library. So I would try to get rid of all your library imports and use the component way instead.

    If you are not using lot of components then it should reduce considerably the size of your bundled file.

    As further explanation:

    When you are using the library way you are importing all these react-bootstrap and all these material-ui components, regardless which ones you are actually using.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-30 19:07

    Have you looked at how you're scripts are being sent over the wire... I had some very simple react components that were up around 300kb each, and that was after the webpack optimizations. After they were gzipped they came down to 38kb. Still sizable - but that's what we get for using tomorrows features today. If you're using node/express to serve static resources, including your javascript - look at compression (https://github.com/expressjs/compression). I'd also suggest looking at the node best practices guide for production https://expressjs.com/en/advanced/best-practice-performance.html If you're not serving files through node, then apache (or other webserver) will have options for compressing text based files.

    0 讨论(0)
  • 2020-11-30 19:25

    UPDATED 05/18 : update UglifyJsPlugin setting for better minification

    I use below configuration for the minification in production code.

     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,
            conditionals: true,
            unused: true,
            comparisons: true,
            sequences: true,
            dead_code: true,
            evaluate: true,
            if_return: true,
            join_vars: true
          },
          output: {
            comments: false,
          },
          exclude: [/\.min\.js$/gi] // skip pre-minified libs
        }),
        new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]), 
        new CompressionPlugin({
          asset: "[path].gz[query]",
          algorithm: "gzip",
          test: /\.js$|\.css$|\.html$/,
          threshold: 10240,
          minRatio: 0
        })
      ],
    
    0 讨论(0)
  • 2020-11-30 19:26

    I find it useful to mention the source-map-explorer utility that helps in knowing what exactly is in your bundle.js file. It can help you identify if there are any unnecessary things in bundle js. you can install the source-map-explorer from npm and use it like

    source-map-explorer yourBundle.js
    

    Besides this, as mentioned by @kimmiju , check if your server is using some compression.

    You can also try to asynchronously load routes (lazy loading in webpack) , so that your entire bundlejs file is not sent in one go , instead it is sent in chunks when user navigates to those routes.

    0 讨论(0)
提交回复
热议问题