Lodash not TreeShaking with Webpack with Webpack 4?

一曲冷凌霜 提交于 2019-12-05 06:23:15

I found the answer

To use lodash with tree shaking we should first install lodash-es & then remove the lodash dependency

Also, it should not be transpiled first, so we make our .babelrc file as follows -

{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ]
  ]
}

Notice, that setting modules to false makes it not transpile

And now the bundle reduces to 16.2kB & 5.79kB gzip

Some code from lodash module will still be used because it is required to run lodash itself, other than that multiply function from ./math.js isn't added in the resulting bundle

I also needed lodash-webpack-plugin for it to be working

Treeshaking works 🎉

I've made some basic repos solving the stated problem -

https://github.com/deadcoder0904/webpack-exam

https://github.com/deadcoder0904/webpack-treeshake

Building off of @deadcoder0904's answer, here's how to do the same with babel-loader in webpack 4 (instead of using .babelrc):

...
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    plugins: ['lodash'],
                    presets: [['env', { modules: false }]]
                }
            }
        },

Note: I wasn't able to get this to work without explicitly importing from 'lodash-es' (even if I pointed lodash-es to lodash in my tsconfig (I'm using typescript). If someone can get this working without having to use the special import { map } from 'lodash-es'; and instead with import { map } from 'lodash'; it would be great to know how!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!