【问题标题】:Webpack treeshaking with exporting const variablesWebpack treeshaking 与导出 const 变量
【发布时间】:2018-09-17 06:36:57
【问题描述】:

我们的设置:
- 角 5.2.x
- 离子 4.4.x.
- Webpack 3.6.x

我们有一个这样的应用结构:

app
  |__features
  |    |__Feature1
  |    |     |__Feature1Service.ts
  |    |     |__Feature1Dto.ts
  |    |     |__index.ts
  |    |
  |    |__Feature2
  |          |__Feature2Service.ts
  |          |__Feature2Dto.ts
  |          |__index.ts
  |
  |__core
       |__SomeCoreStuff.ts
       |__index.ts

在索引文件中,我们导出当前功能之外所需的所有内容,如下所示:

import { Feature1Service } from './Feature1Service';
import { Feature1Dto } from './Feature1Dto';
export const fromFeature1 = { Feature1Service, Feature1Dto };

然后用法看起来像这样,例如在功能 2 中:

import { fromFeature1 } from '../Feature1';

//use Feature1Service but not Feature1Dto
fromFeature1.Feature1Service;

在这种情况下,仅使用const fromFeature1 上的一个属性。

我们的问题是 webpack 的 treeshaking 是否会剥离未使用的导出(在本例中为 Feature1Dto)。如果不是,这会炸毁我们部署的 js 包吗?

【问题讨论】:

    标签: angular typescript ionic-framework webpack


    【解决方案1】:

    fromFeature1.Feature1ServicefromFeature1 对象属性。如果 fromFeature1 正在使用中,则它不是导出并且不能进行 tree-shaking。

    为了使用摇树,应该是:

    export { Feature1Service } from './Feature1Service';
    export { Feature1Dto } from './Feature1Dto';
    

    【讨论】:

    • 如果我们在索引文件中执行 export * from './Feature1Service'; export * from './Feature1Dto'; 然后 import * as fromFeature1 from './Feature1' 执行 treeshaking 是否有效?
    • 是的,tree shakIng 就是这样工作的,至少在当前的 webpack 版本中是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2015-05-04
    • 2015-12-10
    • 2011-09-16
    相关资源
    最近更新 更多