如何解决Javascript/Typescript 中类的交叉引用如何工作?
// classes.ts
export class A extends BaseModel implements IA {
static readonly modelName = 'A';
b?: B;
symbol?: string;
constructor(object: IA | A = {} as IA) {
super(object);
const { symbol,b } = object as A;
this.symbol = symbol;
this.b = b;
}
}
export class B extends BaseModel implements IB {
static readonly modelName = 'B';
a?: A[];
constructor(object: IB | B = {} as IB) {
super(object);
const { a } = object as B;
this.a = a as A[];
}
}
错误是这样的
Uncaught ReferenceError: Cannot access 'B' before initialization
at Module.../../../../libs/platform/src/data/models/common/uom.ts (uom.ts:13)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform/src/data/models/common/common-models.ts (main.js:27248)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform/src/data/models/common/index.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform/src/data/models/index.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform/src/data/index.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform/src/index.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform-frontend/src/core/client/frontend-client.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
at Module.../../../../libs/platform-frontend/src/core/client/index.ts (index.ts:1)
at __webpack_require__ (bootstrap:84)
// babel.config.json
{
"presets": [
"@nrwl/web/babel","@nrwl/react/babel"
],"plugins": [
"babel-plugin-transform-typescript-Metadata"
],"babelrcRoots": [
"*"
]
}
//tsconfig.json
{
"compileOnSave": false,"compilerOptions": {
"downlevelIteration": true,"types": ["jest","node","cypress","reflect-Metadata"],"resolveJsonModule": true,"esModuleInterop": true,"rootDir": ".","sourceMap": false,"declaration": false,"moduleResolution": "node","emitDecoratorMetadata": true,"experimentalDecorators": true,"skipLibCheck": true,"importHelpers": false,"target": "es5","allowJs": true,"typeRoots": ["node_modules/@types"],"lib": [
"es2017","es6","dom","es2016","esnext.asynciterable","es5","scripthost","es2015.promise","es2015.collection"
],"baseUrl": ".","forceConsistentCasingInFileNames": true,"noImplicitReturns": true,"suppressImplicitAnyIndexErrors": true,"noUnusedLocals": true,...
...
}
令人困惑的是它根据 babel 配置正常工作 我正在尝试在我的代码库中添加 inversify,因为我必须在 babel 配置中添加 babel-plugin-transform-typescript-metadata。 这样做之后,我在每个带有交叉引用的类上都会出错,这些错误在添加 babel 插件之前工作正常
- 是什么导致了这些问题?
- 如何根据 babel 配置正常工作?
- 我该怎么做才能修复它,因为它甚至不在可能导致循环依赖的单独文件中
解决方法
显然是与“babel-plugin-transform-typescript-metadata”相关的问题,用“babel-plugin-parameter-decorator”替换该插件后,与循环依赖相关的问题自动解决。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。