---
title: 与转译器一起使用
---

来源：https://mikro-orm.io/docs/usage-with-transpilers

<a id="babel"></a>
## Babel

通过 babel 编译 TS 时，装饰器默认采用的实现方式与 `tsc` 所使用的不同。要让通过 Babel 从装饰器中提取元数据正常工作，你需要使用以下插件：

```json
{
  "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`

最后，你需要把 `BABEL_DECORATORS_COMPAT` 环境变量设为 `true`，以调整装饰器的返回值。

关于这个话题的更多信息可以在这里找到：

- https://github.com/mikro-orm/mikro-orm/issues/840
- https://jonahhallibonetech.medium.com/next-js-9-mikroorm-eb6f6e08e1a1

<a id="swc"></a>
## SWC

通过 SWC 编译 TS 时，默认不会发出装饰器元数据，无论你在 `tsconfig.json` 中指定了什么。此外，当 target 为 "es5"（这是 SWC 的默认值）时，类名默认会被混淆。当表名是从类名推断出来、而不是作为装饰器选项显式指定时，这会引发问题。而要让 SWC 保留类名，又要求 target 为 "es2016" 或更高。为了获得最佳的整体性能，也因为 MikroORM 终究是运行在服务器上，你可能会想把 target 设为 "esnext"。这样 SWC 做的转换最少，产出的代码也最现代。

因此，要让通过 SWC 从装饰器提取元数据以及保留类名都正确工作，你的 `.swcrc` 文件需要如下配置：

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

如果你想启用压缩，可能还需要把 `jsc.keepClassNames` 设为 `true`，并相应地设置 "mangle" 与 "compress" 选项以保留类名。

关于这个话题的更多信息可以在这里找到：

- https://github.com/mikro-orm/mikro-orm/issues/5255
- https://swc.rs/docs/configuration/compilation#jsctransformdecoratormetadata
- https://swc.rs/docs/configuration/compilation#jsckeepclassnames
- https://swc.rs/docs/configuration/minification
