【问题标题】:Typescript removes (tree-shaking) my file/class打字稿删除(摇树)我的文件/类
【发布时间】:2019-05-26 21:33:53
【问题描述】:

假设一个类将自己添加到另一个类,如下所示

bar.ts:

import { Foo } from './foo';

export class Bar {}

Foo.prop = Bar;

还有文件foo.ts

export class Foo {
    public static prop: any;
}

现在,如果想在index.ts中使用它

import { Foo } from './foo';

console.log(Foo.prop); // -> undefined

未定义。看起来bar.ts 根本没有使用(可能是摇树)。所以我可以修复如下:

import { Foo } from './foo';
import { Bar } from './bar';

new Bar(); // trick!
console.log(Foo.prop); // -> Bar

有没有办法告诉 typescript 无论如何都要包含Bar,因为我展示的解决方案很丑。

为了完整起见,这是我的tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "outDir": "./dist",
    "baseUrl": "./",
    "lib": ["es2017", "dom", "dom.iterable"]
  },
  "exclude": ["node_modules", "**/*.spec.ts", "dist"]
}

【问题讨论】:

    标签: typescript tree-shaking


    【解决方案1】:

    Foo.prop = Bar;

    是导致问题的原因,您在 Bar.ts 中执行此操作,在 Foo.ts 中执行此操作,现在当您在 index.ts 中创建 Foo 的新对象时,摇树不会删除 Bar.ts .

    作为一般规则,如果您需要为类添加依赖项,请始终在定义类的文件(本例中为 Foo.ts)中执行此操作

    【讨论】:

    • 我明白,但这对我不起作用,很不幸。我想要这个的原因是因为依赖注入库(npmjs.com/package/di-xxl)最后你有像@Injectable这样的装饰器,它将类注册到DI类(基本上和我的问题描述的一样)。我刚刚将该库迁移到打字稿,现在它不再工作了:(
    • 您可以使用基于 typescript 的 DI 库,例如 typedi(非常简单)或 inversify(一开始有点混乱,但如果您理解它就很强大!)
    • 只有我在这里看到的其他解决方案,所以按照您所做的,并强制在 index.ts 中创建 Bar 类型的对象。
    • 我编写了一个工具,它可以注入导入,以便打字稿使用这些文件。效果很好。我认为 angular 与其@Injectable({ providedIn: 'root'}) 或多或少做同样的事情
    猜你喜欢
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2018-07-08
    • 2021-01-23
    • 2022-01-28
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多