【问题标题】:How to tree-shake exported import?如何摇树导出导入?
【发布时间】:2019-09-26 19:33:39
【问题描述】:

我有 my-module 和以下文件:

src/components/foo.js

export default class Foo { ... }

src/components/bar.js

export default class Bar { ... }

index.js

import Foo from './src/components/foo'
import Bar from './src/components/bar'

export { Foo, Bar }

我的目标是让用户轻松导入FooBar,但不会失去对其中一个进行摇树的能力,以防只使用另一个。

我用 Webpack 测试了以下内容:

import { Foo } from 'my-module'

我得到了Foo,但我在生成的包中也得到了Bar,这不应该发生。防止这种情况的唯一方法似乎是这样做:

import Foo from 'my-module/components/foo'

但我不太喜欢这个,因为用户需要知道模块的内部目录结构。有没有办法可以让以前的导入 tree-shakable?

【问题讨论】:

  • 发生这种情况是因为您在 index.js 中同时导入了 FooBar。尝试在 index.js 中对每个都使用 export { default as Foo } from './src/components/foo,看看是否得到不同的结果?

标签: javascript webpack


【解决方案1】:

这个:

import { Foo } from 'my-module'

实际上确实工作正常,Bar 是 tree-shaken,但前提是 Webpack 处于生产模式。

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2020-07-28
    • 2014-02-04
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多