Webpack import * 搞乱了 tree shaking?

Webpack import * messes tree shaking?

我在这里读到这个 ​​- https://www.thedevelobear.com/post/5-things-to-improve-performance/ - 从库中导入所有东西将不允许 tree shaking 删除它,即使它没有被使用。我不相信这是真的吗?我认为 tree shaking 会识别 none 个函数,除了几个函数被使用,然后删除那些。

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

是的,这是真的。这是通过对 es 模块上的命名导入进行静态分析来完成的。

该工具将静态分析您的导入,并仅从源中复制您声明的内容。如果要 运行 遍历所有代码,找出您从该文件调用的所有函数,返回,删除那些未使用的函数,这将花费大量时间和成本。

如果你有:

import {a} from 'filea'

但你有

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

bundler/tool可以去你的档案里看:

"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

使用当前版本的 Webpack (5.3.0),这不是真的。使用以下文件:

// src/index.js
import * as a from './modules'

console.log(a.foo)
// Or: console.log(a.baz.foo)
// src/modules.js
export const foo = 'foo'
export const bar = 'bar'
export const baz = {
  foo: 'foo',
  bar: 'bar',
}

Webpack 输出:

// dist/main.js
(()=>{"use strict";console.log("foo")})();

基于此Github issue,即使在上一个回答时也不是真的。