> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt.

# Node.js

在本文档中，你将学习如何使用 Rslib 构建 Node.js 库，你可在 [示例](https://github.com/rstackjs/rstack-examples/tree/main/rslib) 中查看 Node.js 相关演示项目。

## 创建 Node.js 项目

使用 `create-rslib` 创建 Rslib + Node.js 项目。只需执行以下命令：


```sh [npm]
npm create rslib@latest
```

```sh [yarn]
yarn create rslib
```

```sh [pnpm]
pnpm create rslib@latest
```

```sh [bun]
bun create rslib@latest
```

然后在提示 "Select template" 时选择 `Node.js`。

## 在现有 Rslib 项目中使用

Rslib 为 Node.js 项目提供无缝支持，允许以最少的配置轻松构建 Node.js 项目。

例如，在 `rslib.config.ts` 中：

```ts title="rslib.config.ts"
import { defineConfig } from '@rslib/core';

export default defineConfig({});
```

## 用于 Node.js 的 target

Rslib 中 [target](/zh/config/rsbuild/output.md#outputtarget) 的默认值为 `"node"`，这与 Rsbuild 的 target 默认值不同。

当 target 为 `"node"`，Rslib 会为 Node.js 调整一些配置。例如，[output.externals](/zh/config/rsbuild/output.md#outputtarget) 将 external 内置 Node.js 模块，而 [shims](/zh/config/lib/shims.md) 将在 CJS 产物中为 `import.meta.url` 添加 shim。

### Externals

所有 Node.js [built-in modules](https://nodejs.org/docs/latest/api/) 会默认被 external。

### Shims

- `global`: 保持原样，建议使用 [globalThis](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) 替代.
- `__filename`: 当以 ESM 格式输出时，替换 `__filename` 为 `fileURLToPath(import.meta.url)`.
- `__dirname`: 当以 ESM 格式输出时，替换 `__dirname` 为 `dirname(fileURLToPath(import.meta.url))`.



