Webpack import * messes tree shaking?

拟墨画扇 提交于 2019-12-11 14:27:51

问题


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, '🐻');

// Do this

import { fill } from ‘lodash’

let array = [1, 2, 3];
fill(array, '🐻');

回答1:


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



来源:https://stackoverflow.com/questions/53415558/webpack-import-messes-tree-shaking

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