Webpack import * messes tree shaking?

2019-08-25 01:23发布

I read this here - https://www.thedevelobear.com/post/5-things-to-improve-performance/ - that doing importing all things from a library will not allow tree shaking to remove it, even if it is not used. I don't believe this, is it really true? I would think that tree shaking would identify that none of the functions except a couple were used, and then remove those.

There is a really easy way to reduce bundle size by just checking your imports. When performing methods or components from 3rd party libraries, make sure you import only the things you need, not the whole library itself. For instance, if you’re using lodash and need the fill method, import it directly instead of calling it on lodash object:

// Instead of this

import _ from ‘lodash’

let array = [1, 2, 3];
_.fill(array, '                

1条回答
不美不萌又怎样
2楼-- · 2019-08-25 02:17

Yes it is true. This is done via static analysis on the named imports on the es modules.

The tool is going to statically analyze your imports and just copy from the source those that you had stated. If it were to run throughout all your code, identify all the functions that you called from that file, go back, remove those that aren't used, it would be costly and would take much more time.

if you have:

import {a} from 'filea'

but you have

export const a = 'a';
export const b = 'b';

The bundler/tool can go to your file, see:

"oh, one imported just a from filea, let me pull just it."

https://webpack.js.org/guides/tree-shaking/

https://medium.com/webpack/better-tree-shaking-with-deep-scope-analysis-a0b788c0ce77

https://medium.com/@zwegrzyniak/webpack-4-1-and-es-modules-esm-dd0bd7dca4da

查看更多
登录 后发表回答