Disable tree shaking in Webpack 4

So, my other answer does help, but not by much. While it avoids tree shaking, this just causes the build to inline the full copy of lodash into every bundle. For a codebase like ours with 100s of entry points, this is still very inefficient. It made the build faster than 6 minutes, but no where near the original 3 minutes.

I the end I used externals to conditionally ignore Lodash imports entirely, only in dev. This can be done something like

    externals: {
        ...(isProduction ? {} : { 'lodash-es': '_' }),
    },

You would then need to write some logic to conditionally include a script tag for the full Lodash build only on dev into your head tag.

So this isn't really a generic answer to this question – more specific to our use case of Lodash and a very large codebase. For other codebases or dependencies, disabling tree shaking might be the right answer.


Well, I couldn't find anything in the docs, but this is a relatively inoffensive workaround:

Add

{
    test: () => !env.production,
    sideEffects: true,
},

To your module.rules array. That rule will match every file when running in dev mode, and no files when running in prod mode. When it matches a file, it tells Webpack (falsely) that the file has side effects, and so cannot be tree-shaken.

This brought our build times back from 6 minutes to 3 minutes on dev.

Hardly ideal but in the absence of a proper config option from Webpack this will have to do.

It also seems better than other alternatives, like enabling Babel CJS module transforms only in dev, since that could cause subtle bugs that only appear in production due to the differences in semantics/behaviour between mutable CJS modules and immutable ES modules.

Tags:

Webpack