Skip to main content
Version: 6.4

与转译器一起使用

Babel

通过 babel 编译 TS 时,装饰器的默认处理方式与 tsc 使用的实现方式不同。要使通过 Babel 从装饰器中提取元数据有效,我们需要使用以下插件:

¥When compiling TS via babel, decorators are by default handled different implementation than what tsc uses. To make the metadata extraction from decorators via Babel work, we need to do use following plugins:

{
"plugins": [
"babel-plugin-transform-typescript-metadata",
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}

确保首先安装插件:yarn add -D babel-plugin-transform-typescript-metadata @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties

¥Make sure to install the plugins first: yarn add -D babel-plugin-transform-typescript-metadata @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties

最后,我们需要将 BABEL_DECORATORS_COMPAT 环境变量设置为 true 以调整装饰器的返回值。

¥Lastly we need to set the BABEL_DECORATORS_COMPAT environment variable to true to adjust the return value of decorators.

有关此主题的更多信息,请参阅此处:

¥More information about this topic can be found here:

SWC

通过 SWC 编译 TS 时,默认情况下不会发出装饰器元数据,无论你在 tsconfig.json 中指定了什么。此外,当目标是 SWC 的默认设置 "es5" 时,默认情况下类名会被破坏。当表的名称是从类名推断出来的,而不是明确指定为装饰器选项时,这会导致问题。反过来告诉 SWC 保留类名需要 "es2016" 或更高的目标。为了获得最佳整体性能,并且由于 MikroORM 最终在服务器上运行,你可能需要将目标设置为 "esnext"。这样,SWC 会进行尽可能少的转换并生成最现代的代码。

¥When compiling TS via SWC, decorator metadata is not emitted by default, regardless of what you may have specified in tsconfig.json. In addition, class names are mangled by default when the target is "es5" which is SWC's default. This causes problems when the name of a table is inferred from the class name, as opposed to being explicitly specified as a decorator option. Telling SWC to preserve the class names in turn requires a target of "es2016" or higher. For the best overall performance, and because MikroORM is ultimately running on a server, you may want to set the target to "esnext". That way, SWC does the fewest transformations possible and produces the most modern code possible.

因此,为了使从装饰器中提取元数据和通过 SWC 保存类名正常工作,我们需要在 .swcrc 文件中进行以下配置:

¥So, to make the metadata extraction from decorators and class name preservation via SWC work correctly, we need the following config in our .swcrc file:

{
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true
},
"transform": {
"decoratorMetadata": true,
"legacyDecorator": true
},
"target": "esnext",
"minify": false
}
}

如果你想要启用最小化,你可能还需要将 jsc.keepClassNames 设置为 true,以及等效的 "mangle" 和 "compress" 选项以保留类名。

¥If you'd like to enable minification, you may also need to set jsc.keepClassNames to true, as well as the equivalent "mangle" and "compress" options to preserve class names.

有关此主题的更多信息,请参阅此处:

¥More information about this topic can be found here: