# SWC（快速编译器）

来源：https://docs.nestjs.com/recipes/swc

[SWC](https://swc.rs/)（Speedy Web Compiler）是一个可扩展的、基于 Rust 的平台，既可用于编译，也可用于打包。把 SWC 与 Nest CLI 搭配使用，是显著加快开发流程的直截了当的做法。

> info **提示** SWC 的速度约是默认 TypeScript 编译器的 **20 倍**。

#### 安装

开始之前，先安装几个包：

```bash
$ npm i --save-dev @swc/cli @swc/core
```

#### 开始使用

安装完成后，就可以在 Nest CLI 中使用 `swc` 构建器了，如下所示：

```bash
$ nest start -b swc
# 或者 nest start --builder swc
```

> info **提示** 如果你的仓库是 monorepo，请参阅 [Monorepo](/recipes/swc#monorepo) 一节。

除了传入 `-b` 标志，你也可以在 `nest-cli.json` 文件中把 `compilerOptions.builder` 属性设为 `"swc"`：

```json
{
  "compilerOptions": {
    "builder": "swc"
  }
}
```

要自定义构建器的行为，请传入一个含两个属性的对象，即 `type`（`"swc"`）与 `options`，如下所示：

```json
{
  "compilerOptions": {
    "builder": {
      "type": "swc",
      "options": {
        "swcrcPath": "infrastructure/.swcrc",
      }
    }
  }
}
```

例如，要让 SWC 编译 `.jsx` 与 `.tsx` 文件，请使用下面的配置：

```json
{
  "compilerOptions": {
    "builder": {
      "type": "swc",
      "options": { "extensions": [".ts", ".tsx", ".js", ".jsx"] }
    },
  }
}

```

要以监视模式运行应用，请使用下面的命令：

```bash
$ nest start -b swc -w
# 或者 nest start --builder swc --watch
```

#### 类型检查

与默认的 TypeScript 编译器不同，SWC 自身不做任何类型检查。要打开类型检查，请使用 `--type-check` 标志：

```bash
$ nest start -b swc --type-check
```

该命令指示 Nest CLI 在运行 SWC 的同时以 `noEmit` 模式运行 `tsc`，由后者异步执行类型检查。除了传入 `--type-check` 标志，你也可以在 `nest-cli.json` 文件中把 `compilerOptions.typeCheck` 属性设为 `true`：

```json
{
  "compilerOptions": {
    "builder": "swc",
    "typeCheck": true
  }
}
```

#### CLI 插件（SWC）

`--type-check` 标志会自动执行 **NestJS CLI 插件** 并生成一个序列化的元数据文件，应用随后可以在运行时加载它。

#### SWC 配置

SWC 构建器已预配置好，以契合 NestJS 应用的需求。不过，你可以在根目录创建一个 `.swcrc` 文件并按需调整选项，从而自定义配置：

```json
{
  "$schema": "https://swc.rs/schema.json",
  "sourceMaps": true,
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "dynamicImport": true
    },
    "baseUrl": "./"
  },
  "minify": false
}
```

> info **提示** SWC 构建器输出的模块格式与 TypeScript 编译器相同：当你的 `package.json` 文件设置了 `"type": "module"` 时输出 ES 模块（新项目的默认值），否则输出 CommonJS。`.swcrc` 中的 `module` 设置会覆盖这一行为。

#### Monorepo

> info **提示** 自 NestJS v12 起，monorepo 默认使用 Rspack 构建器，它已通过 Rspack 内置的 `swc-loader` 用 SWC 编译你的代码。下面的配置仅适用于已废弃的 webpack 构建器。

如果你的仓库是 monorepo，那么就不能使用 `swc` 构建器，而要配置 `webpack` 使用 `swc-loader`。

首先，安装所需的包：

```bash
$ npm i --save-dev swc-loader
```

安装完成后，请在应用的根目录创建一个 `webpack.config.js` 文件，内容如下：

```js
const swcDefaultConfig = require('@nestjs/cli/lib/compiler/defaults/swc-defaults').swcDefaultsFactory().swcOptions;

module.exports = {
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: {
          loader: 'swc-loader',
          options: swcDefaultConfig,
        },
      },
    ],
  },
};
```

#### Monorepo 与 CLI 插件

如果你使用了 CLI 插件，`swc-loader` 不会自动加载它们。作为替代，你必须另外创建一个文件来手动加载。为此，请在 `main.ts` 文件旁创建一个 `generate-metadata.ts` 文件，内容如下：

```ts
import { PluginMetadataGenerator } from '@nestjs/cli/lib/compiler/plugins/plugin-metadata-generator.js';
import { ReadonlyVisitor } from '@nestjs/swagger/plugin';

const generator = new PluginMetadataGenerator();
generator.generate({
  visitors: [new ReadonlyVisitor({ introspectComments: true, pathToSource: import.meta.dirname })],
  outputDir: import.meta.dirname,
  watch: true,
  tsconfigPath: 'apps/<name>/tsconfig.app.json',
});
```

> info **提示** 本示例使用的是 `@nestjs/swagger` 插件，但你也可以使用任何你选定的插件。

`generate()` 方法接受以下选项：

|                    |                                                                                                |
| ------------------ | ---------------------------------------------------------------------------------------------- |
| `watch`            | 是否监视项目的变化。                                                                            |
| `tsconfigPath`     | `tsconfig.json` 文件的路径。相对于当前工作目录（`process.cwd()`）。                             |
| `outputDir`        | 保存元数据文件的目录路径。                                                                      |
| `visitors`         | 用于生成元数据的 visitor 数组。                                                                 |
| `filename`         | 元数据文件的名称。默认为 `metadata.ts`。                                                        |
| `printDiagnostics` | 是否把诊断信息打印到控制台。默认为 `true`。                                                     |

最后，在另一个终端窗口中用下面的命令运行 `generate-metadata` 脚本：

```bash
$ npx ts-node src/generate-metadata.ts
# 或者 npx ts-node apps/{YOUR_APP}/src/generate-metadata.ts
```

#### 常见陷阱

如果你在应用中使用 TypeORM、MikroORM 或任何其他 ORM，可能会遇到循环导入问题。SWC 处理不好 **循环导入**，因此请使用下面的变通写法：

```typescript
@Entity()
export class User {
  @OneToOne(() => Profile, (profile) => profile.user)
  profile: Relation<Profile>; // <--- 注意这里用的是 "Relation<>" 类型，而不是只写 "Profile"
}
```

> info **提示** `Relation` 类型从 `typeorm` 包导出。

这样一来，属性的类型就不会被保存进转译后代码的属性元数据中，从而避免循环依赖问题。

如果你的 ORM 没有提供类似的变通写法，你可以自行定义这个包装类型：

```typescript
/**
 * 用于规避 ESM 模块循环依赖问题的包装类型，
 * 该问题由反射元数据保存属性类型引起。
 */
export type WrapperType<T> = T; // WrapperType === Relation
```

对于项目中所有的[循环依赖注入](/fundamentals/circular-dependency)，你也需要使用上面这个自定义包装类型：

```typescript
@Injectable()
export class UsersService {
  constructor(
    @Inject(forwardRef(() => ProfileService))
    private readonly profileService: WrapperType<ProfileService>,
  ) {}
}
```

### Jest + SWC

要把 SWC 与 Jest（CommonJS 项目的默认测试运行器）搭配使用，请安装以下包：

```bash
$ npm i --save-dev jest @swc/core @swc/jest
```

安装完成后，请按下面的内容更新你的 `package.json` 或 `jest.config.js` 文件（取决于你的配置方式）：

```json
{
  "jest": {
    "transform": {
      "^.+\\.(t|j)s?$": ["@swc/jest"]
    }
  }
}
```

此外，请在 `.swcrc` 文件中加入 `legacyDecorator` 与 `decoratorMetadata` 这两个 `transform` 属性：

```json
{
  "$schema": "https://swc.rs/schema.json",
  "sourceMaps": true,
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "dynamicImport": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    },
    "baseUrl": "./"
  },
  "minify": false
}
```

如果你在项目中使用了 NestJS CLI 插件，就必须手动运行 `PluginMetadataGenerator`。更多内容参见 [Monorepo 与 CLI 插件](/recipes/swc#monorepo-and-cli-plugins)一节。

### Vitest

[Vitest](https://vitest.dev/) 是一个快速、轻量的测试运行器，专为与 Vite 配合而设计。使用 ES 模块（默认方式）的新 NestJS 项目已经配置好了 Vitest。本节介绍如何配置 Vitest，让它用 SWC 构建你的测试文件。

#### 安装

开始之前，先安装所需的包：

```bash
$ npm i --save-dev vitest unplugin-swc @swc/core @vitest/coverage-v8
```

#### 配置

请在应用的根目录创建一个 `vitest.config.ts` 文件，内容如下：

```ts
import { resolve } from 'node:path';
import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
  },
  plugins: [
    // 用 SWC 构建测试文件时必须保留这一项
    swc.vite({
      // 显式设置模块类型，避免从 `.swcrc` 配置文件继承该值
      module: { type: 'es6' },
    }),
  ],
  resolve: {
    alias: {
      // 确保 Vitest 正确解析 TypeScript 路径别名
      'src': resolve(import.meta.dirname, './src'),
    },
  },
});
```

这个配置文件设置了 Vitest 环境、根目录与 SWC 插件。你还应为 e2e 测试单独创建一个配置文件（例如 `vitest.config.e2e.ts`），并在其中额外加上一个 `include` 字段，用来指定测试文件的 glob 模式：

```ts
import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    include: ['**/*.e2e-spec.ts'],
    globals: true,
    root: './',
  },
  plugins: [swc.vite()],
});
```

此外，你可以设置 `alias` 选项，以支持测试中的 TypeScript 路径：

```ts
import swc from 'unplugin-swc';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    include: ['**/*.e2e-spec.ts'],
    globals: true,
    alias: {
      '@src': './src',
      '@test': './test',
    },
    root: './',
  },
  resolve: {
    alias: {
      '@src': './src',
      '@test': './test',
    },
  },
  plugins: [swc.vite()],
});
```

### 路径别名

Vitest 不会自动解析 `src/` 这类 TypeScript 路径别名，这可能在测试期间导致依赖解析错误。要解决这个问题，请在 `vitest.config.ts` 文件中加入下面的 `resolve.alias` 配置：

```ts
import { resolve } from 'node:path';

export default defineConfig({
  resolve: {
    alias: {
      'src': resolve(import.meta.dirname, './src'),
    },
  },
});
```

这样就能确保 Vitest 正确解析模块导入，避免出现与缺少依赖相关的错误。

#### 更新 E2E 测试中的导入

请把所有使用 `import * as request from 'supertest'` 的 E2E 测试导入改为 `import request from 'supertest'`。`supertest` 是导出函数的 CommonJS 模块，而在 Vitest 这样的 ES 模块环境中，命名空间导入不可调用，因此你需要使用默认导入。

最后，更新 `package.json` 文件中的测试脚本：

```json
{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest",
    "test:cov": "vitest run --coverage",
    "test:debug": "vitest --inspect-brk --no-file-parallelism",
    "test:e2e": "vitest run --config ./vitest.config.e2e.ts"
  }
}
```

这些脚本分别用于运行测试、监视变化、生成代码覆盖率报告，以及启动调试会话。其中 `test:e2e` 脚本会用专门的配置文件运行 E2E 测试。

> info **提示** 一个可用的示例见 [nest-vitest 仓库](https://github.com/TrilonIO/nest-vitest)。
