简体   繁体   English

打字稿删除(树木)我的文件/类

[英]Typescript removes (tree-shaking) my file/class

Suppose a class adds itself to an other class as follows 假设一个类将自己添加到另一个类,如下所示

bar.ts : bar.ts

import { Foo } from './foo';

export class Bar {}

Foo.prop = Bar;

And file foo.ts 并提交文件foo.ts

export class Foo {
    public static prop: any;
}

Now, if would like to use this in index.ts 现在,如果想在index.ts使用它

import { Foo } from './foo';

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

It is undefined. 这是未定义的。 It looks like that bar.ts is not used at all (probably tree shaking). 看起来bar.ts根本就没用过(可能是树摇晃)。 So I can fix that as follows: 所以我可以解决如下问题:

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

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

Is there a way to tell typescript to include Bar anyway, because the solution I showed is ugly. 有没有办法告诉打字稿包括Bar ,因为我展示的解决方案很难看。

For completeness, here is my tsconfig.json 为了完整性,这是我的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"]
}

Foo.prop = Bar;

is what is causing the issue, you're doing this in Bar.ts, do this in Foo.ts, now when you create a new object of Foo in index.ts, tree shaking won't remove Bar.ts. 是什么导致了这个问题,你在Bar.ts中这样做,在Foo.ts中这样做,现在当你在index.ts中创建一个新的Foo对象时,树摇动不会删除Bar.ts.

As a general rule, if you need to add a dependency to a class,always do that in the file where the class is defined (Foo.ts in this case) 作为一般规则,如果需要向类添加依赖项,请始终在定义类的文件中执行此操作(在本例中为Foo.ts)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM