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

# Output

顶级的 `output` 包含一组选项，指导 Rspack 如何以及在哪里输出 bundles、assets，以及使用 Rspack 打包或加载的任何其他内容。

- **类型：** `Object`

## output.assetModuleFilename

- **类型：** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** `'[hash][ext][query]'`

与 [`output.filename`](#outputfilename) 类似，但适用于[资源模块](/zh/guide/features/asset-module.md)。

`[name]`、`[file]`、`[query]`、`[fragment]`、`[base]` 和 `[path]` 在使用数据 URI 替换构建的资源中被设置为空字符串。

Asset module 输出的文件名称。这个值可以被 [rules\[\].generator.filename](/zh/config/module-rules.md#rulesgenerator) 覆盖。

:::info Asset module 作为一个单独的文件输出的情况

- 模块类型为 `'asset'` 且 asset 满足 [`rules[].parser.dataUrlCondition`](/zh/config/module-parser.md#assetdataurlcondition) 设定值
- 模块类型为 `'asset/resource'`

:::

## output.asyncChunks

- **类型：** `boolean`
- **默认值：** `true`

用于控制通过动态导入加载的模块，是被输出为独立的异步 chunk，还是被打包进已有的 chunk 中。

- `true`：通过 `import()` 加载的模块会被拆分为独立的异步 chunk。这些 chunk 会作为单独的文件输出，并在运行时按需加载。这样可以启用代码拆分，减小初始包体积。
- `false`：通过动态导入加载的模块不会生成单独的文件，而是被直接打包进现有的 chunk 中。此时不会额外生成异步 chunk 文件。

```js title="rspack.config.mjs"
export default {
  output: {
    asyncChunks: false,
  },
};
```

## output.bundlerInfo


[Added in v2.0.0](https://github.com/web-infra-dev/rspack/releases/tag/v2.0.0)

> 在 1.x 版本中，你可以使用 `experiments.rspackFuture.bundlerInfo`。

- **类型：**

  ```ts
  type BundlerInfo = {
    version?: string;
    bundler?: string;
    force?: boolean | ('version' | 'uniqueId')[];
  };
  ```

用于在生成产物中注入当前使用的 Rspack 信息。其中：

- `version`：用于指定 Rspack 版本，默认读取 `@rspack/core/package.json` 中的 `version` 字段。
- `bundler`：用于指定打包工具名称，默认为 `rspack`
- `force`：是否强制注入 Rspack 信息，会以运行时模块的形式加入到产物中，默认为 `false`，可通过数组选择强制注入的项目。

默认情况下，在检测到代码中使用了 `import.meta.rspackVersion` 或 `import.meta.rspackUniqueId` 时，会按需注入对应信息。可将 `force` 设定为 `true` 始终注入：

- [`import.meta.rspackVersion`](/zh/api/runtime-api/module-variables.md#importmetarspackversion)：注入版本信息
- [`import.meta.rspackUniqueId`](/zh/api/runtime-api/module-variables.md#importmetarspackuniqueid)：注入打包工具唯一 ID

```js title="rspack.config.mjs"
export default {
  output: {
    bundlerInfo: { force: true },
  },
};
```

## output.chunkFilename

- **类型：** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** 当 [`output.filename`](#outputfilename) 为字符串时，根据其推断；否则为 `'[id].js'`。

这个选项决定了非初始块文件的名称。有关可能值的详细信息，请参见 [`output.filename`](/zh/config/output.md#outputfilename) 选项。

注意，这些文件名需要在运行时生成，以便发送 chunk 的请求。因此，像 `[name]` 和 `[chunkhash]` 这样的占位符需要在 Rspack 运行时将 chunk id 映射到占位符值添加到输出 bundle 中。这会增加大小，并且可能会在任何 chunk 的占位符值更改时使 bundle 的缓存失效。

未配置此选项时，Rspack 根据 [`output.filename`](#outputfilename) 推断默认值：

- 如果 `output.filename` 是包含 `[name]`、`[id]`、`[chunkhash]` 或 `[contenthash]` 的字符串，则直接复用该字符串。其中 `[name]` 不会被替换成 `[id]`。
- 否则，Rspack 会在文件名前添加 `[id].`，保留目录和查询字符串。
- 如果 `output.filename` 是函数，则默认为 `'[id].js'`。Rspack 不会调用该函数来推断 `output.chunkFilename`。

| `output.filename`     | 默认的 `output.chunkFilename` |
| --------------------- | -------------------------- |
| `'[name].js'`         | `'[name].js'`              |
| `'[name].mjs'`        | `'[name].mjs'`             |
| `'scripts/bundle.js'` | `'scripts/[id].bundle.js'` |
| 函数                    | `'[id].js'`                |

你也可以显式指定其他文件名模板：

```js title="rspack.config.mjs"
export default {
  output: {
    chunkFilename: '[id].js',
  },
};
```

:::tip
查看 [文件名占位符](/zh/config/filename-placeholders.md) 了解更多信息。
:::

使用函数：

```js title="rspack.config.mjs"
export default {
  output: {
    chunkFilename: (pathData) => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};
```

## output.chunkFormat

- **类型：** `false | 'array-push' | 'commonjs' | 'module' | string`
- **默认值：** 根据 [`target`](/zh/config/target.md) 和 [`output.module`](#outputmodule) 的配置推断

chunk 产物的格式，一般来说，target 为 web 或 webworker'时会使用 `'array-push'` 格式；为 ESM 时会使用 `'module'` 格式；为 node.js 时会使用 `'commonjs'` 格式，插件可能会添加其他格式。

:::tip
这个选项的默认值取决于 [`target`](/zh/config/target.md) 和 [`output.module`](#outputmodule) 设置。要了解更多详情，请在 Rspack [默认设置中](https://github.com/web-infra-dev/rspack/blob/main/packages/rspack/src/config/defaults.ts)搜索 `"chunkFormat"`。
:::

```js title="rspack.config.mjs"
export default {
  output: {
    chunkFormat: 'commonjs',
  },
};
```

## output.chunkLoading

- **类型：** `false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import' | string`

加载 chunk 的方式，默认值会根据 [`target`](/zh/config/target.md) 和 [`chunkFormat`](#outputchunkformat) 的配置而决定，一般来说，target 为 web 时会使用 `'jsonp'` 来加载 chunk；为 ESM 时会使用 `'import'` 来加载 chunk；为 webworker 时会使用 `'import-scripts'` 来加载 chunk；为 node.js 时会使用 `'require'` 来加载 chunk；为 async node.js 时会使用 `'async-node'`（`fs.readFile` + `vm.runInThisContext`）来加载 chunk，插件可能会添加其他格式。

:::tip
这个选项的默认值取决于 [`target`](/zh/config/target.md) 和 [`output.chunkFormat`](#outputchunkformat) 设置。要了解更多详情，请在 Rspack [默认设置中](https://github.com/web-infra-dev/rspack/blob/main/packages/rspack/src/config/defaults.ts)搜索 `"chunkLoading"`。
:::

```js title="rspack.config.mjs"
export default {
  output: {
    chunkLoading: 'async-node',
  },
};
```

## output.chunkLoadingGlobal

- **类型：** `string`
- **默认值：** 根据 [`output.uniqueName`](/zh/config/output.md#outputuniquename) 推断

此选项决定了 Rspack 用于加载 chunk 的全局变量。

```js title="rspack.config.mjs"
export default {
  output: {
    chunkLoadingGlobal: 'myCustomFunc',
  },
};
```

## output.chunkLoadTimeout

- **类型：** `number`
- **默认值：** `120000`

Chunk 加载的超时时间（毫秒）。

```js title="rspack.config.mjs"
export default {
  output: {
    chunkLoadTimeout: 30000, // Chunk 加载会在 30 秒后超时
  },
};
```

## output.clean

- **类型：** `boolean | { keep?: string | RegExp | ((path: string) => boolean) }`
- **默认值：** `false`

在输出产物之前清理输出目录中的文件。将 `clean` 设为 `true` 可启用清理：

```js title="rspack.config.mjs"
export default {
  output: {
    clean: true, // Clean the output directory before emit.
  },
};
```

通过 `clean.keep` 保留指定路径：

```js title="rspack.config.mjs"
export default {
  output: {
    clean: {
      keep: 'ignored/dir', // keep these assets under 'dist/ignored/dir'.
    },
  },
};
```

也可以使用正则表达式匹配要保留的路径：

```js title="rspack.config.mjs"
export default {
  output: {
    clean: {
      keep: /ignored\/dir/, // keep these assets under 'dist/ignored/dir'.
    },
  },
};
```

如需自定义匹配逻辑，可以通过函数返回 `true` 来保留文件：

```js title="rspack.config.mjs"
export default {
  output: {
    clean: {
      keep: (path) => path.includes('ignored/dir'), // keep these assets under 'dist/ignored/dir'.
    },
  },
};
```

## output.compareBeforeEmit

- **类型：** `boolean`
- **默认值：** `true`

告知 Rspack 在写入产物文件时检查文件是否已经存在并且拥有相同内容。

:::warning
当在文件系统中已经存在有相同内容的文件时，Rspack 将不会写入产物文件。
:::

```js title="rspack.config.mjs"
export default {
  output: {
    compareBeforeEmit: false,
  },
};
```

## output.crossOriginLoading

- **类型：** `false | 'anonymous' | 'use-credentials'`
- **默认值：** `false`

通过 `crossOriginLoading` 配置项，你可以为动态加载的 chunks 设置 [crossorigin 属性](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin)。

当 `target` 为 `'web'` 时，Rspack 会动态创建 `<script>` 和 `<link>` 标签来加载异步的 JavaScript 和 CSS 资源。如果这些资源的 URL 在其他域名下，且 `crossOriginLoading` 不为 `false`，那么 Rspack 会为 `<script>` 和 `<link>` 标签添加 `crossorigin` 属性。

**可选值**

`crossOriginLoading` 有以下可选值：

- `false`: 不设置 [crossorigin 属性](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin)。
- `'anonymous'`：将 `crossorigin` 设置为 `'anonymous'`，不包含用户凭据来跨域加载资源。
- `'use-credentials'`：将 `crossorigin` 设置为 `'use-credentials'`，包含用户凭据来跨域加载资源。

**示例**

比如将 [output.publicPath](#outputpublicpath) 设置为 `https://example.com/`，并将 `output.crossOriginLoading` 设置为 `'anonymous'`：

```js title="rspack.config.mjs"
import path from 'node:path';

export default {
  output: {
    publicPath: 'https://example.com/',
    crossOriginLoading: 'anonymous',
  },
};
```

当 Rspack 在加载异步的 JavaScript 资源时，会生成如下的 HTML：

```html
<script src="https://example.com/foo.js" crossorigin="anonymous"></script>
```

## output.cssChunkFilename

- **类型：** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** 当 [`output.chunkFilename`](/zh/config/output.md#outputchunkfilename) 不为函数时，根据 [`output.chunkFilename`](/zh/config/output.md#outputchunkfilename) 推断；否则为 `'[id].css'`。

此选项决定了非初始（non-initial）CSS chunk 文件的名称，参阅 [`output.filename`](/zh/config/output.md#outputfilename)，了解可能的值。

当 `output.chunkFilename` 为字符串时，Rspack 会将其中的 `.js`、`.mjs` 或 `.cjs` 扩展名替换为 `.css`，并保留查询字符串。当其为函数时，默认值为 `'[id].css'`，不会调用该函数来推断 CSS 文件名。

在这里不能指定绝对路径。不过，可以随意包括用 `'/'` 分隔的文件夹。这个指定的路径将与 [`output.path`](#outputpath) 值结合，以精确定位磁盘上的位置。

## output.cssFilename

- **类型：** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** 当 [`output.filename`](#outputfilename) 为字符串时，根据其推断；否则为 `'[id].css'`。

此选项决定了 CSS 文件的名称，参阅 [`output.filename`](/zh/config/output.md#outputfilename)，了解可能的值。

当 `output.filename` 为字符串时，Rspack 会将其中的 `.js`、`.mjs` 或 `.cjs` 扩展名替换为 `.css`，并保留查询字符串。如果不包含这些扩展名，则保持字符串不变。

| `output.filename`        | 默认的 `output.cssFilename` |
| ------------------------ | ------------------------ |
| `'scripts/[name].js'`    | `'scripts/[name].css'`   |
| `'[name].mjs?version=1'` | `'[name].css?version=1'` |
| 函数                       | `'[id].css'`             |

使用函数配置 JavaScript 文件名时，如果需要按名称输出 CSS 产物，可以单独配置 CSS 文件名：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: () => 'scripts/[name].js',
    cssFilename: 'styles/[name].css',
  },
};
```

在这里**不能**指定绝对路径。不过，可以随意包括用 `'/'` 分隔的文件夹。这个指定的路径将与 [`output.path`](#outputpath) 值结合，以精确定位磁盘上的位置。

## output.devtoolFallbackModuleFilenameTemplate

- **类型：**

```ts
type DevtoolFallbackModuleFilenameTemplate =
  string | ((context: ModuleFilenameTemplateContext) => string);
```

- **默认值：** `undefined`

当模板字符串或函数产生重复时使用的备用内容。

详见 [`output.devtoolModuleFilenameTemplate`](/zh/config/output.md#outputdevtoolmodulefilenametemplate).

## output.devtoolModuleFilenameTemplate

- **类型：**

```ts
type DevtoolModuleFilenameTemplate =
  string | ((context: ModuleFilenameTemplateContext) => string);
```

- **默认值：** `webpack://[namespace]/[resource-path]?[loaders]'`

此选项仅在 [`devtool`](/zh/config/devtool.md) 使用了需要模块名称的选项时使用。

自定义每个 source map 的 `sources` 数组中使用的名称。可以通过传递模板字符串或者函数来完成。例如，当使用 `devtool: 'eval'`，默认值是：

```js title="rspack.config.mjs"
export default {
  output: {
    devtoolModuleFilenameTemplate:
      'webpack://[namespace]/[resource-path]?[loaders]',
  },
};
```

模板字符串支持以下模式：

| 模板                        | 描述                                                          |
| ------------------------- | ----------------------------------------------------------- |
| \[absolute-resource-path] | 绝对路径文件名                                                     |
| \[relative-resource-path] | 模块资源相对于 source map 文件所在目录的相对路径；对于内联 source map，则相对于产物文件所在目录 |
| \[all-loaders]            | 自动和显式的 loader，并且参数取决于第一个 loader 名称                          |
| \[hash]                   | 模块标识符的 hash                                                 |
| \[id]                     | 模块标识符                                                       |
| \[loaders]                | 显式的 loader，并且参数取决于第一个 loader 名称                             |
| \[resource]               | 用于解析文件的路径和用于第一个 loader 的任意查询参数                              |
| \[resource-path]          | 不带任何查询参数，用于解析文件的路径                                          |
| \[namespace]              | 模块命名空间。在构建成为一个 library 之后，通常也是 library 名称，否则为空              |

当使用一个函数，同样的选项要通过 `info` 参数并使用驼峰式：

```js title="rspack.config.mjs"
export default {
  output: {
    devtoolModuleFilenameTemplate: (info) => {
      return `webpack:///${info.resourcePath}?${info.loaders}`;
    },
  },
};
```

如果多个模块产生相同的名称，使用 [`output.devtoolFallbackModuleFilenameTemplate`](/zh/config/output.md#outputdevtoolfallbackmodulefilenametemplate) 来代替这些模块。

## output.devtoolNamespace

- **类型：** `string`
- **默认值：** [`output.uniqueName`](#outputuniquename)

此选项确定 [`output.devtoolModuleFilenameTemplate`](/zh/config/output.md#outputdevtoolmodulefilenametemplate) 使用的模块名称空间。未指定时的默认值为：[`output.uniqueName`](/zh/config/output.md#outputuniquename)。在加载多个通过 Rspack 构建的 library 时，用于防止 source map 中源文件路径冲突。

例如，如果你有两个 `library`，分别使用命名空间 `library1` 和 `library2`，并且都有一个文件 `./src/index.js`（可能具有不同内容），它们会将这些文件暴露为 `webpack://library1/./src/index.js` 和 `webpack://library2/./src/index.js`。

## output.enabledChunkLoadingTypes

- **类型：** `('jsonp' | 'import-scripts' | 'require' | 'async-node' | string)[]`
- **默认值：** 根据 [`output.chunkLoading`](#outputchunkloading)、[`output.workerChunkLoading`](#outputworkerchunkloading) 及 Entry 的 chunkLoading 的配置推断

启用用于入口 chunk 加载类型的列表。将由 Rspack 自动填充，仅在使用函数作为入口选项并从那里返回 chunkLoading 选项时需要。

```js title="rspack.config.mjs"
export default {
  output: {
    enabledChunkLoadingTypes: ['jsonp', 'require'],
  },
};
```

## output.enabledLibraryTypes

- **类型：** `string[]`
- **默认值：** 根据 [output.library](#outputlibrary) 和 [Entry](/zh/config/entry.md) 的配置推断

入口点可用的 library 类型列表。

```js title="rspack.config.mjs"
export default {
  output: {
    enabledLibraryTypes: ['module'],
  },
};
```

## output.enabledWasmLoadingTypes

- **类型：** `('...' | 'fetch' | 'async-node' | 'universal')[]`
- **默认值：** 根据 [`output.wasmLoading`](#outputwasmloading) 及 [`output.workerWasmLoading`](#outputworkerwasmloading) 的配置推断

开启可用的 Wasm 加载类型的运行时模块打包。

```js title="rspack.config.mjs"
export default {
  output: {
    enabledWasmLoadingTypes: ['fetch'],
  },
};
```

## output.environment

- **类型：**

```ts
type Environment = {
  /** The environment supports arrow functions ('() => { ... }'). */
  arrowFunction?: boolean;
  /** The environment supports async function and await ('async function () { await ... }'). */
  asyncFunction?: boolean;
  /** The environment supports BigInt as literal (123n). */
  bigIntLiteral?: boolean;
  /** The environment supports const and let for variable declarations. */
  const?: boolean;
  /** The environment supports computed property names in object literals ('{ [expr]: value }'). */
  computedProperty?: boolean;
  /** The environment supports destructuring ('{ a, b } = obj'). */
  destructuring?: boolean;
  /** The environment supports 'document' variable. */
  document?: boolean;
  /** The environment supports an async import() function to import ECMAScript modules. */
  dynamicImport?: boolean;
  /** The environment supports an async import() when creating a worker, only for web targets at the moment. */
  dynamicImportInWorker?: boolean;
  /** The environment supports `import.meta.dirname` and `import.meta.filename`. */
  importMetaDirnameAndFilename?: boolean;
  /** The environment supports 'for of' iteration ('for (const x of array) { ... }'). */
  forOf?: boolean;
  /** The environment supports 'globalThis'. */
  globalThis?: boolean;
  /** The environment supports { fn() {} } */
  methodShorthand?: boolean;
  /** The environment supports ECMAScript Module syntax to import ECMAScript modules (import ... from '...'). */
  module?: boolean;
  /**
   * Determines if the node: prefix is generated for core module imports in environments that support it.
   * This is only applicable to Rspack runtime code.
   * */
  nodePrefixForCoreModules?: boolean;
  /** The environment supports optional chaining ('obj?.a' or 'obj?.()'). */
  optionalChaining?: boolean;
  /** The environment supports logical assignment ('a ||= b'). */
  logicalAssignment?: boolean;
  /** The environment supports template literals. */
  templateLiteral?: boolean;
};
```

`output.environment` 定义 Rspack 在生成运行时代码时可以使用的 ECMAScript 语言特性和宿主环境特性。

该选项仅影响 Rspack 生成的 runtime 代码和辅助函数，不会影响源代码的语法降级。

### 默认值

`output.environment` 的默认值由 [target](/zh/config/target.md) 自动推断。

Rspack 会基于 `target` 识别目标环境支持的语言能力，例如：

- 若目标浏览器已支持箭头函数，Rspack 会默认使用箭头函数以缩短 runtime 代码
- 若 `target` 指向特定 Node 版本，Rspack 会根据该版本的语法能力推断对应字段

通常你无需手动设置此选项，除非你希望强制启用或禁用某些语法。当你手动配置此选项时，可以覆盖 Rspack 自动推断的结果，显式声明目标环境是否支持某些语法特性，从而影响 runtime 代码的输出形式。

### 示例

例如，当 `target` 为 `['web', 'es2018']` 时，Rspack 会默认启用 `const` 语法，你可以通过手动配置 `output.environment.const: false` 来禁用它。此时 Rspack 会生成使用 `var` 声明变量的 runtime 代码。

```js title="rspack.config.mjs"
export default {
  target: ['web', 'es2018'],
  output: {
    environment: {
      const: false,
    },
  },
};
```

## output.filename

- **类型：** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** [output.module](#outputmodule) 为 `true` 时为 `'[name].mjs'`，否则为 `'[name].js'`

这个选项决定了输出的 JavaScript bundle 文件名称。这些 bundle 将会被写入 [`output.path`](#outputpath) 指定的目录下。

对于单个 [Entry](/zh/config/entry.md) 来说，你可以使用一个固定名称，如：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: 'bundle.js',
  },
};
```

然而，当通过多个 Entry、代码分割或各种插件创建多个包时，你应该使用以下替换之一来给每个包一个唯一的名字...

:::info 对于拆分成多个 bundle 的情况的描述

Rspack 会对用户输入的代码进行代码分割优化，这些优化可能包括但不限于：code splitting、bundle splitting，或通过其他插件实现的代码分割等。
这些代码分割的行为会导致生成多个 bundle，因此 bundle 的文件名需要动态生成。

:::

使用 [Entry](/zh/config/entry.md) 名称：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: '[name].bundle.js',
  },
};
```

使用内部 chunk id：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: '[id].bundle.js',
  },
};
```

使用从生成内容中生成的哈希值：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: '[contenthash].bundle.js',
  },
};
```

将多个替换组合起来：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: '[name].[contenthash].bundle.js',
  },
};
```

:::tip
查看 [文件名占位符](/zh/config/filename-placeholders.md) 了解更多信息。
:::

使用函数返回文件名：

```js title="rspack.config.mjs"
export default {
  output: {
    filename: (pathData) => {
      return pathData.chunk.name === 'main' ? '[name].js' : '[name]/[name].js';
    },
  },
};
```

这个选项被称为文件名，但你仍然可以使用类似 `js/[name]/bundle.js` 的东西来创建文件夹结构。

请注意，此选项不会影响到按需加载块的输出文件。它只影响最初加载的输出文件。对于按需加载的块文件，使用的是 [`output.chunkFilename`](#outputchunkfilename) 选项。由加载器创建的文件也不会受到影响。在这种情况下，你可能需要尝试特定加载器提供的可用选项。

## output.globalObject

- **类型：** `string`
- **默认值：** 根据 [`target`](/zh/config/target.md) 推断：目标环境提供 `global` 时为 `'global'`，否则在支持 `globalThis` 时为 `'globalThis'`，其余情况为 `'self'`。

当输出为 library 时，尤其是当 `library.type` 为 `'umd'` 时，此选项将决定使用哪个全局对象来挂载 library。为了使 UMD 构建在浏览器和 Node.js 上均可用，应将 `output.globalObject` 设置为 `'this'`。

例如，未配置 `output.globalObject` 时：

| `target`            | 默认的 `output.globalObject` |
| ------------------- | ------------------------- |
| `'web'`             | `'self'`                  |
| `['web', 'es2020']` | `'globalThis'`            |
| `'node'`            | `'global'`                |

入口点的返回值将会使用 `output.library.name` 赋值给全局对象。依赖于 `target` 配置项，全局对象将会发生对应的改变，例如：`self`, `global` 或者 `globalThis`。

示例：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'myLib',
      type: 'umd',
    },
    filename: 'myLib.js',
    globalObject: 'this',
  },
};
```

## output.hashDigest

- **类型：** `string`
- **默认值：** `'hex'`

在生成哈希时使用的编码方式。使用 `'base64'` 作为文件名可能会有问题，因为其中包含 `/` 字符。同样 `'latin1'` 也可能包含任何字符。

## output.hashDigestLength

- **类型：** `number`
- **默认值：** `16`

要使用的 hash 摘要的长度，详见 [Hash 长度](/zh/config/filename-placeholders.md#hash-长度)。

```js title="rspack.config.mjs"
export default {
  output: {
    hashDigestLength: 8,
  },
};
```

## output.hashFunction

- **类型：** `'md4' | 'xxhash64' | 'sha256'`
- **默认值：** `'xxhash64'`

指定要使用的哈希算法。

```js title="rspack.config.mjs"
export default {
  output: {
    hashFunction: 'xxhash64',
  },
};
```

## output.hashSalt

- **类型：** `string`
- **默认值：** `undefined`

可选的 salt，用于更新哈希值。

## output.hotUpdateChunkFilename

- **类型：** `string`
- **默认值：** 当 [`output.module`](#outputmodule) 为 `true` 时，为 `'[id].[fullhash].hot-update.mjs'`，否则为 `'[id].[fullhash].hot-update.js'`。

自定义热更新文件的文件名，参阅 [`output.filename`](#outputfilename)，了解可能的值。只有 `[fullhash]` 和 `[id]` 可用作占位符。

```js title="rspack.config.mjs"
export default {
  output: {
    hotUpdateChunkFilename: '[id].[fullhash].hot-update.js',
  },
};
```

:::tip
通常你不需要更改 `output.hotUpdateChunkFilename`。
:::

## output.hotUpdateGlobal

- **类型：** `string`
- **默认值：** `"rspackHotUpdate" + output.uniqueName`

仅当 [`target`](/zh/config/target.md) 设置为 `"web"` 时使用，它使用 JSONP 来加载热更新。

JSONP 函数用于异步加载热更新块。

具体可以参阅 [output.chunkLoadingGlobal](#outputchunkloadingglobal)。

## output.hotUpdateMainFilename

- **类型：** `string`
- **默认值：** 当 [`output.module`](#outputmodule) 为 `true` 时，为 `'[runtime].[fullhash].hot-update.json.mjs'`，否则为 `'[runtime].[fullhash].hot-update.json'`。

自定义热更新清单文件的文件名。只有 `[fullhash]` 和 `[runtime]` 可用作占位符。

:::tip
通常你不需要更改 `output.hotUpdateMainFilename`。
:::

## output.iife

- **类型：** `boolean`
- **默认值：** 当 [`output.module`](#outputmodule) 为 `true` 时为 `false`，否则为 `true`。

让 Rspack 为生成的代码添加 [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) 包装器。

```js title="rspack.config.mjs"
export default {
  output: {
    iife: true,
  },
};
```

## output.importFunctionName

- **类型：** `string`
- **默认值：** `'import'`

内部 `import()` 函数的名称. 可用于 polyfilling，例如通过 [`dynamic-import-polyfill`](https://github.com/GoogleChromeLabs/dynamic-import-polyfill).

```js title="rspack.config.mjs"
export default {
  output: {
    importFunctionName: '__import__',
  },
};
```

## output.importMetaName

- **Type:** `string`
- **Default:** `'import.meta'`

内部 `import.meta` 对象的名字，可将其换成 polyfill 的对象。

```js title="rspack.config.mjs"
export default {
  output: {
    importMetaName: 'pseudoImport.meta',
  },
};
```

## output.library

输出一个库，为你的入口做导出。

- **类型：** `string | string[] | object`

一起来看一个简单的示例。

```js title="rspack.config.mjs"
export default {
  entry: './src/index.js',
  output: {
    library: 'MyLibrary',
  },
};
```

假设你在 `src/index.js` 的入口中导出了如下函数：

```js
export function hello(name) {
  console.log(`hello ${name}`);
}
```

此时，变量 `MyLibrary` 将与你的入口文件所导出的文件进行绑定，下面是如何使用 Rspack 构建的库的实现：

```html
<script src="https://example.org/path/to/my-library.js"></script>
<script>
  MyLibrary.hello('rspack');
</script>
```

在上面的例子中，我们为 `entry` 设置了一个入口文件，然而 Rspack 可以接受 [多个入口](/zh/config/entry.md)，例如一个 `array` 或者一个 `object`。

1. 如果你将 `entry` 设置为一个 `array`，那么只有数组中的最后一个会被暴露。

   ```js title="rspack.config.mjs"
   export default {
     entry: ['./src/a.js', './src/b.js'], // 只有在 b.js 中导出的内容才会被暴露
     output: {
       library: 'MyLibrary',
     },
   };
   ```

2. 如果你将 `entry` 设置为一个 `object`，所以入口都可以通过 `library` 的 `array` 语法暴露：

   ```js title="rspack.config.mjs"
   export default {
     entry: {
       a: './src/a.js',
       b: './src/b.js',
     },
     output: {
       filename: '[name].js',
       library: ['MyLibrary', '[name]'], // name is a placeholder here
     },
   };
   ```

   假设 `a.js` 与 `b.js` 导出名为 `hello` 的函数，这就是如何使用这些库的方法：

   ```html
   <script src="https://example.org/path/to/a.js"></script>
   <script src="https://example.org/path/to/b.js"></script>
   <script>
     MyLibrary.a.hello('rspack');
     MyLibrary.b.hello('rspack');
   </script>
   ```

### output.library.amdContainer

- **类型：** `string`

在全局为 AMD 模块添加 `define`/`require` 函数的容器。

:::warning
请注意，`amdContainer` 的值必须设置为全局变量。
:::

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      amdContainer: 'window["clientContainer"]',
      type: 'amd', // or 'amd-require'
    },
  },
};
```

这将产生以下 bundle：

```js
window['clientContainer'].define(/*define args*/); // or 'amd-require' window['clientContainer'].require(/*require args*/);
```

### output.library.name

指定库的名称。

- **类型：**`string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}`

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
    },
  },
};
```

### output.library.type

配置将库暴露的方式。

- **类型：** `string`

  类型默认包括 `'var'`、`'module'`、`'modern-module'`、`'assign'`、`'assign-properties'`、`'this'`、`'window'`、`'self'`、`'global'`、`'commonjs'`、`'commonjs2'`、`'commonjs-module'`、`'commonjs-static'`、`'amd'`、`'amd-require'`、`'umd'`、`'umd2'`、`'jsonp'` 和 `'system'`，除此之外也可以通过插件添加。

对于接下来的示例，我们将会使用 `_entry_return_` 表示被入口点返回的值。

#### 暴露一个变量

这些选项将入口点的返回值（例如，入口点导出的内容）分配给 [`output.library.name`](#outputlibraryname) 中配置的名称，无论 bundle 被包含在什么作用域中。

##### type: 'var'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
    },
  },
};
```

让你的库加载之后，**入口起点的返回值** 将会被赋值给一个变量：

```js
var MyLibrary = _entry_return_;

// 在加载了 `MyLibrary` 的单独脚本中
MyLibrary.doSomething();
```

##### type: 'assign'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign',
    },
  },
};
```

这将生成一个隐含的全局变量，它有可能重新分配一个现有的值（请谨慎使用）：

```js
MyLibrary = _entry_return_;
```

请注意，如果 `MyLibrary` 没有在你的库之前定义，那么它将会被设置在全局作用域。

##### type: 'assign-properties'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'assign-properties',
    },
  },
};
```

与 [`type: 'assign'`](#type-assign) 相似但是更安全，因为如果 `MyLibrary` 已经存在的话，它将被重用：

```js
// 仅在当其不存在是创建 MyLibrary
MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;
// 然后复制返回值到 MyLibrary
// 与 Object.assign 行为类似

// 例如，你像下面这样在你的入口导出一个 `hello` 函数
export function hello(name) {
  console.log(`Hello ${name}`);
}

// 在另外一个已经加载 MyLibrary 的脚本中
// 你可以像这样运行 `hello` 函数
MyLibrary.hello('World');
```

#### 通过对象赋值暴露

这些配置项分配入口点的返回值（例如：无论入口点导出的什么内容）到一个名为 [`output.library.name`](#outputlibraryname) 的对象中。

##### type: 'this'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'this',
    },
  },
};
```

**入口起点的返回值** 将会被赋值给 this 对象下的 `output.library.name` 属性。`this` 的含义取决于你：

```js
this['MyLibrary'] = _entry_return_;

// 在一个单独的脚本中
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // 如果 `this` 为 window 对象
```

##### type: 'window'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'window',
    },
  },
};
```

**入口起点的返回值** 将会被赋值给 `window` 对象下的 `output.library.name`。

```js
window['MyLibrary'] = _entry_return_;

window.MyLibrary.doSomething();
```

##### type: 'global'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'global',
    },
  },
};
```

**入口起点的返回值** 将会被复制给全局对象下的 `output.library.name`。取决于 [`target`](/zh/config/target.md) 值，全局对象可以分别改变,例如，`self`、`global` 或者 `globalThis`。

```js
global['MyLibrary'] = _entry_return_;

global.MyLibrary.doSomething();
```

##### type: 'commonjs'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'commonjs',
    },
  },
};
```

**入口起点的返回值** 将使用 `output.library.name` 赋值给 `exports` 对象。顾名思义，这是在 CommonJS 环境中使用。

```js
exports['MyLibrary'] = _entry_return_;

require('MyLibrary').doSomething();
```

:::warning
注意，不设置 `output.library.name` 将导致入口起点返回的所有属性都被赋值给给定的对象；不检查现有的属性名。
:::

#### 模块定义系统

这些配置项将生成一个带有完整 header 的 bundle，以确保与各种模块系统兼容。`output.library.name` 配置项在不同的 `output.library.type` 中有不同的含义。

##### type: 'module'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // 不要指定 `name`
      type: 'module',
    },
  },
};
```

输出 ESM 模块。

这是一条更偏向兼容性的 ESM library 路径：Rspack 仍沿用常规的 chunk / runtime 渲染流程，再把入口导出转换成 `export` 语句。它更适合较简单的 ESM 库输出，或者你只需要 webpack 风格 `module` 语义的场景。

##### type: 'modern-module'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // 不要指定 `name`
      type: 'modern-module',
    },
  },
};
```

这项配置会启用 Rspack 为 ESM 库单独设计的渲染路径，直接输出 `import` / `export`，并支持库场景下的 tree-shaking、scope hoisting、code splitting 以及 [`output.library.preserveModules`](#outputlibrarypreservemodules)。

:::tip `module` 和 `modern-module` 的区别

- `module` 仍走常规的 chunk / runtime 渲染流程，属于更接近 webpack 兼容语义的 ESM 输出。
- `modern-module` 会由专用的 ESM library 插件接管 chunk 渲染、链接、scope hoisting 和 splitChunks，更适合发布可 tree-shake、可 code-split 的 ESM 库。
- `modern-module` 当前是为补齐库场景 ESM 能力而单独引入的类型；等能力进一步稳定后，计划与 `module` 收敛为同一个 `library.type`。
- `preserveModules` 仅在 `modern-module` 下可用。
- 当你配置了 `output.library` 且 `output.module = true` 时，如果没有显式指定 `output.library.type`，Rspack 当前默认会使用 `modern-module`。
- 不允许在同一次编译中把 `modern-module` 和其他 `library.type` 混用，因为它会同时影响 chunk loading、chunk 渲染和 scope hoisting 的行为。

:::

##### type: 'commonjs2'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs2',
    },
  },
};
```

**入口起点的返回值** 将会被赋值给 `module.exports`。顾名思义，这是在 Node.js（CommonJS）环境中使用的：

```js
module.exports = _entry_return_;

require('MyLibrary').doSomething();
```

如果我们指定 `output.library.name` 为 `type: commmonjs2`，你的入口起点的返回值将会被赋值给 `module.exports.[output.library.name]`。

:::tip
在考虑 CommonJS 与 CommonJS2 之间的区别？虽然它们很相似，但是它们之间有一些细微的差别，这些差别在 Rspack 的上下文中通常是不相关的。（要获取更多详细内容，请 [阅读这个 issue](https://github.com/webpack/webpack/issues/1114)。）
:::

##### type: 'commonjs-static'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // note there's no `name` here
      type: 'commonjs-static',
    },
  },
};
```

单个导出将被设置为 `module.exports` 中的属性。名称中的“static”是指输出是静态可分析的，因此具名导出可以通过 Node.js 导入到 ESM 中：

输入：

```js
export function doSomething() {}
```

输出：

```js
function doSomething() {}

exports.doSomething = __webpack_exports__.doSomething;
```

消费（CommonJS）:

```js
const { doSomething } = require('./output.cjs'); // doSomething => [Function: doSomething]
```

消费（ESM）:

```js
import { doSomething } from './output.cjs'; // doSomething => [Function: doSomething]
```

:::tip
当源代码是用 ESM 编写的，并且输出应该兼容 CJS 和 ESM 时，这是很有用的。获取更多详情，请阅读该 [issue](https://github.com/webpack/webpack/issues/14998) 或者 [这篇文档](https://dev.to/jakobjingleheimer/configuring-commonjs-es-modules-for-nodejs-12ed)（尤其是 [这个章节](https://dev.to/jakobjingleheimer/configuring-commonjs-es-modules-for-nodejs-12ed#publish-only-a-cjs-distribution-with-property-exports)）。
:::

:::tip 如何选择 CommonJS 的 `library.type`

| 类型                | 写入目标                | 更适合的场景                                 |
| ----------------- | ------------------- | -------------------------------------- |
| `commonjs`        | `exports[...]`      | 兼容已有依赖 `exports` 对象的历史配置；更偏兼容写法        |
| `commonjs2`       | `module.exports`    | 通用的 Node.js / CJS 库输出；大多数新配置优先选它       |
| `commonjs-module` | `module.exports`    | 当前与 `commonjs2` 等价，主要用于兼容历史 webpack 配置 |
| `commonjs-static` | `exports.foo = ...` | 需要让 Node.js ESM 能够对 CJS 产物做具名导入        |

Rspack 当前保留这些写法主要是为了兼容 webpack 生态，并没有在配置层面对它们做废弃。对于新项目，通常优先考虑 `commonjs2` 或 `commonjs-static`；只有在迁移既有配置、或明确依赖 `exports` 赋值语义时，再使用 `commonjs` / `commonjs-module`。

:::

##### type: 'amd'

这将使库作为一个 AMD 模块暴露出来。

AMD 模块要求入口 chunk（例如，通过 `<script>` 标签加载的第一个脚本）具有特定属性，例如 `define` 和 `require`，这些通常由 RequireJS 或任何兼容的加载器（如 almond）提供。否则，直接加载生成的 AMD 包将导致错误，例如 `define is not defined`。

配置如下配置：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd',
    },
  },
};
```

生成的输出将被定义为名为 `"MyLibrary"`，比如：

```js
define('MyLibrary', [], function () {
  return _entry_return_;
});
```

包可以作为脚本标签的一部分被包含，并且可以像这样调用：

```js
require(['MyLibrary'], function (MyLibrary) {
  // Do something with the library...
});
```

如果 `output.library.name` 未定义，则生成以下内容。

```js
define(function () {
  return _entry_return_;
});
```

直接使用 `<script>` 标签加载这个包将无法按预期工作，或者根本无法工作（在使用 almond 加载器的情况下）。它只能通过 RequireJS 兼容的异步模块加载器并通过该文件的实际路径来工作。因此，在这种情况下，如果这些文件直接暴露在服务器上，`output.path` 和 `output.filename` 可能会变得非常重要。

##### type: 'amd-require'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'amd-require',
    },
  },
};
```

这会将你的输出打包成一个立即执行的 AMD `require(dependencies, factory)` 包装器。

`amd-require` 类型允许使用 AMD 依赖项，而不需要后续的单独调用。与 `amd` 类型一样，这取决于在加载 Rspack 输出的环境中是否有适当的 require 函数可用。

使用这种类型时，库名称不能被使用。

##### type: 'umd'

这将在所有模块定义下暴露你的库, 允许它与 CommonJS、AMD 和作为全局变量工作。可以查看 [UMD Repository](https://github.com/umdjs/umd) 获取更多内容。

在这种情况下，你需要使用 `library.name` 属性命名你的模块：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
    },
  },
};
```

最终的输出为：

```js
(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  else root['MyLibrary'] = factory();
})(global, function () {
  return _entry_return_;
});
```

请注意，根据[对象赋值部分](#通过对象赋值暴露)，省略 `library.name` 将导致入口起点返回的所有属性直接赋值给根对象。示例：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      type: 'umd',
    },
  },
};
```

输出将会是：

```js
(function webpackUniversalModuleDefinition(root, factory) {
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else {
    var a = factory();
    for (var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  }
})(global, function () {
  return _entry_return_;
});
```

你可以为 `library.name` 指定一个对象，每个目标的名称不同：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: {
        root: 'MyLibrary',
        amd: 'my-library',
        commonjs: 'my-common-library',
      },
      type: 'umd',
    },
  },
};
```

##### type: 'system'

这将会把你的库暴露为一个 [`System.register`](https://github.com/systemjs/systemjs/blob/master/docs/system-register.md) 模块。

System 模块要求当 bundle 执行时，全局变量 `System` 出现在浏览器中。编译的 `System.register` 格式允许你在没有额外配置的情况下使用 `System.import('/bundle.js')`，并将你的 bundle 加载到系统模块注册表中。

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      type: 'system',
    },
  },
};
```

输出：

```js
System.register([], function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
  return {
    execute: function () {
      // ...
    },
  };
});
```

除了设置 `output.library.type` 为 `system`，还要将 `output.library.name` 添加到配置中，输出的 bundle 将以库名作为 `System.register` 的参数：

```js
System.register(
  'MyLibrary',
  [],
  function (__WEBPACK_DYNAMIC_EXPORT__, __system_context__) {
    return {
      execute: function () {
        // ...
      },
    };
  },
);
```

#### 其他类型

**type: 'jsonp'**

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'jsonp',
    },
  },
};
```

这将把你的入口返回值包装在一个 JSONP 中。

```js
MyLibrary(_entry_return_);
```

库的依赖项将由 [externals](/zh/config/externals.md) 配置定义。

### output.library.export

指定哪一个导出应该被暴露为一个库。

- **类型：** `string | string[]`
- **默认值：** `undefined`

默认情况下为 `undefined`，将导出整个（命名空间）对象。下述 demo 演示了使用 [`output.library.type: 'var'`](#type-var) 配置型产生的作用。

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: 'default',
    },
  },
};
```

入口点的默认导出将会被赋值为库名称：

```js
// 如果你的库有默认导出
var MyLibrary = _entry_return_.default;
```

你可以传递一个数组给 `output.library.export`，它将被解析为要分配给库名称的模块路径：

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'var',
      export: ['default', 'subModule'],
    },
  },
};
```

这里是库代码：

```js
var MyLibrary = _entry_return_.default.subModule;
```

### output.library.auxiliaryComment

在 UMD 包装器中添加注释。

- **类型：** `string | { amd?: string, commonjs?: string, commonjs2?: string, root?: string }`
- **默认值：** `undefined`

为每个 `umd` 类型插入相同的注释，将 `auxiliaryComment` 设置为 string。

```js title="rspack.config.mjs"
export default {
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: 'Test Comment',
    },
  },
};
```

这将产生以下结果：

```js
(function webpackUniversalModuleDefinition(root, factory) {
  //Test Comment
  if (typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  //Test Comment
  else if (typeof define === 'function' && define.amd) define([], factory);
  //Test Comment
  else if (typeof exports === 'object') exports['MyLibrary'] = factory();
  //Test Comment
  else root['MyLibrary'] = factory();
})(self, function () {
  return _entry_return_;
});
```

对于细粒度控制，可以传递一个对象：

```js title="rspack.config.mjs"
export default {
  mode: 'development',
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      auxiliaryComment: {
        root: 'Root Comment',
        commonjs: 'CommonJS Comment',
        commonjs2: 'CommonJS2 Comment',
        amd: 'AMD Comment',
      },
    },
  },
};
```

### output.library.umdNamedDefine

- **类型：** `boolean`
- **默认值：** `undefined`

当使用 `output.library.type: "umd"` 时，将 `output.library.umdNamedDefine` 设置为 `true` 将会把 AMD 模块命名为 UMD 构建。否则使用匿名 `define`。

```js
module.exports = {
  output: {
    library: {
      name: 'MyLibrary',
      type: 'umd',
      umdNamedDefine: true,
    },
  },
};
```

AMD module 将会是这样：

```js
define('MyLibrary', [], factory);
```

### output.library.preserveModules

- **类型：** `string`
- **默认值：** `undefined`

:::info
仅在 `library.type` 为 `modern-module` 时生效。
:::

当启用后，Rspack 会保留传入目录下模块的原始文件结构。每个模块会被输出为单独的文件，保持与源码相同的相对路径。

`preserveModules` 是一种特殊的打包形式——可以将其理解为 **bundle + splitChunks，其中每个模块会被拆分为单独的 chunk**。与 bundleless 工具不同，Rspack 仍然会执行完整的打包流程（tree shaking、scope hoisting、代码压缩等），只是将输出拆分为每个模块对应一个输出文件。

:::warning
**Barrel 文件可能会丢失导出。** 由于 `preserveModules` 仍然是一种打包形式，只有 entry 的导出会被保留。如果 barrel 文件（例如从其他模块重新导出的 `index.ts`）不是 entry，其重新导出的内容不会被保留在输出中。如果确实需要严格暴露导出，请将对应模块设为 entry。
:::

```js title="rspack.config.mjs"
import path from 'node:path';

export default {
  output: {
    library: {
      type: 'modern-module',
      preserveModules: path.resolve('./src'),
    },
  },
};
```

## output.module

- **类型：** `boolean`
- **默认值：** `false`

是否以 ESM 模块的形式输出 JavaScript 文件。

当启用时，[`output.iife`](#outputiife) 默认为 `false`，[`output.scriptType`](#outputscripttype) 默认为 `'module'`。显式配置的值优先于这些默认值。

配置 [`output.library.type`](#outputlibrarytype) 为 'module' 或 'modern-module' 会自动将 `output.module` 设为 `true`。

```js title="rspack.config.mjs"
export default {
  output: {
    module: true,
  },
};
```

## output.path

- **类型：** `string`
- **默认值：** `path.resolve(process.cwd(), 'dist')`

输出文件目录的绝对路径。


**ESM**

```js title="rspack.config.mjs"
import path from 'node:path';

export default {
  output: {
    path: path.resolve(import.meta.dirname, 'dist/assets'),
  },
};
```


**CJS**

```js title="rspack.config.cjs"
const path = require('node:path');

module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist/assets'),
  },
};
```


注意 `[fullhash]` 将会被替换为构建过程中的 hash 值。

:::warning

- 路径中不能包含感叹号（!），因为感叹号在 Rspack 中被用作 loader 语法。
- 相对路径会基于 `context` 进行解析。

:::

## output.pathinfo

- **类型：** `boolean | 'verbose'`
- **默认值：** `false`

控制是否在生成的 bundle 中插入与模块相关的注释。这些注释有助于调试、分析打包结果以及理解 tree shaking 行为。

- `true`: 启用基础的注释输出，包括模块路径信息。
- `false`: 不输出任何注释，这是默认行为。
- `'verbose'`：输出更详细的信息，例如模块导出、运行时信息、tree shaking 信息和 `bailout` 原因。适合排查构建问题或深入分析构建结果。

例如将 `pathinfo` 设置为 `true`：

```js title="rspack.config.mjs"
export default {
  output: {
    pathinfo: true,
  },
};
```

生成的代码中会包含类似的注释：

```js
/*!**********************!*\
  !*** ./src/index.js ***!
  \**********************/
```

:::warning
pathinfo 主要用于开发调试。这些注释会增加 bundle 体积，同时可能泄露源文件结构，请避免在生产环境中启用。
:::

## output.publicPath

- **类型：** `'auto' | string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **默认值：** 当 [target](/zh/config/target.md) 支持 `document` 或 `importScripts` 时为 `'auto'`，否则为 `''`。

用于设置打包后的静态资源文件（如 JS、CSS、图片等）的 URL 路径前缀。

例如，`'web'` 和 `'webworker'` 目标默认为 `'auto'`，而 `'node'` 默认为空字符串。使用空字符串时，资源 URL 不会添加额外前缀。

```js title="rspack.config.mjs"
export default {
  output: {
    publicPath: '/assets/',
  },
};
```

参考 [资源基础路径](/zh/guide/features/asset-base-path.md) 了解完整用法。

## output.scriptType

- **类型：** `false | 'text/javascript' | 'module'`
- **默认值：** `false`

该选项允许使用自定义脚本类型（例如 `<script type="module" ...>`）来加载异步块。

:::tip
如果 `output.module` 设置为 `true`，则 `output.scriptType` 将默认为 `'module'` 而不是 `false`。
:::

```js title="rspack.config.mjs"
export default {
  output: {
    scriptType: 'module',
  },
};
```

## output.sourceMapFilename

- **类型：** `string`
- **默认值：** `'[file].map[query]'`

配置 source map 文件的命名方式。仅当 [`devtool`](/zh/config/devtool.md) 设置为 `'source-map'` 时生效，此时会输出文件。

可以使用 [`output.filename`](#outputfilename) 中的 `[name]`、`[id]`、`[fullhash]` 和 `[chunkhash]` 替换符。此外，还可以使用 [文件名占位符](/zh/config/filename-placeholders.md) 中在文件级别列出的替换符。

## output.strictModuleErrorHandling

- **类型：** `boolean`
- **默认值：** `false`

按照 ES modules 规范处理 module 加载时的错误，会有性能损失。

```js title="rspack.config.mjs"
export default {
  output: {
    strictModuleErrorHandling: true,
  },
};
```

## output.strictModuleExceptionHandling

- **Types:** boolean

告诉 Rspack 当 require 模块出现错误时，移除模块的缓存。

## output.trustedTypes

- **类型：** `true | string | object`
- **默认值：** `undefined`

控制 [Trusted Types](https://web.dev/trusted-types) 兼容性。启用此选项，Rspack 将检测已实现了 Trusted Types，并使用 Trusted Types 来创建它动态加载的脚本 URL。应用在运行带有 [require-trusted-types-for](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) 内容安全策略指令下的应用程序。

默认情况下是不启用。将其设置为 `true` 时，Rspack 会启用 Trusted Types，并从 [`output.uniqueName`](#outputuniquename) 推导策略名称。

```js title="rspack.config.mjs"
export default {
  output: {
    trustedTypes: true,
  },
};
```

### output.trustedTypes.policyName

- **类型：** `string`
- **默认值：** 从 [`output.uniqueName`](#outputuniquename) 推导

Rspack 创建用于加载 bundle chunk 的 Trusted Types 策略名称。当策略名称需要匹配 CSP `trusted-types` 允许列表时，可以使用此选项。

如果省略 `policyName`，Rspack 会从 [`output.uniqueName`](#outputuniquename) 推导策略名称，并将不支持的字符替换为 `_`。如果推导结果为空，则回退为 `'rspack'`。字符串简写 `trustedTypes: 'my-policy'` 等价于设置 `trustedTypes.policyName`。

```js title="rspack.config.mjs"
export default {
  output: {
    trustedTypes: {
      policyName: 'my-application#rspack',
    },
  },
};
```

### output.trustedTypes.onPolicyCreationFailure

- **类型：** `"stop" | "continue"`
- **默认值：** `"stop"`

确定当 [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) 未能正确执行时，是继续加载还是异常终止。未能正确执行可能是由于策略名称不在 CSP 的 `trusted-types` 列表中或策略名称重复而使得 `trustedTypes.createPolicy(...)` 执行失败。

```js title="rspack.config.mjs"
export default {
  output: {
    trustedTypes: {
      policyName: 'my-application#rspack',
      onPolicyCreationFailure: 'continue',
    },
  },
};
```

## output.uniqueName

- **类型：** `string`
- **默认值：** 按以下优先级依次推导：
  1. [`output.library`](#outputlibrary) 的 `name`
  2. `context` 目录下 `package.json` 的 `name`
  3. `''`（空字符串）

该选项用于标识当前构建的唯一名称，主要用于避免多个 Rspack 应用在同一全局环境中运行时，其运行时代码发生冲突。

`output.uniqueName` 会影响以下配置项的默认值：

- [output.chunkLoadingGlobal](#outputchunkloadingglobal)
- [output.hotUpdateGlobal](#outputhotupdateglobal)
- [output.devtoolNamespace](#outputdevtoolnamespace)
- [output.trustedTypes.policyName](#outputtrustedtypespolicyname)

你也可以覆盖默认值：

```js title="rspack.config.mjs"
export default {
  output: {
    uniqueName: 'my-package-xyz',
  },
};
```

## output.wasmLoading

- **类型：** `false | 'fetch' | 'async-node' | 'universal'`
- **默认值：** 根据 [`target`](/zh/config/target.md)、[`output.module`](#outputmodule) 和 [`output.environment`](#outputenvironment) 推断。

用于设置加载 WebAssembly 模块的方式。设为 `false` 可以禁用 WebAssembly 加载。

目标环境支持通过 fetch 加载 WebAssembly 时，Rspack 选择 `'fetch'`；否则，提供 Node.js 内置模块时选择 `'async-node'`。当混合目标对这些能力的支持不一致时，支持动态导入的 ESM 输出可以使用 `'universal'`。如果无法选择加载方式，则默认为 `false`。

其他输出配置保持默认时，示例如下：

| `target`                                                 | `output.module` | 默认的 `output.wasmLoading` |
| -------------------------------------------------------- | --------------- | ------------------------ |
| `'web'` 或 `'webworker'`                                  | `false`         | `'fetch'`                |
| `'electron-renderer'`                                    | `false`         | `'fetch'`                |
| `'node'` 或 `'async-node'`                                | `false`         | `'async-node'`           |
| `'electron-main'`、`'electron-preload'` 或 `'node-webkit'` | `false`         | `'async-node'`           |
| `['web', 'node']`                                        | `true`          | `'universal'`            |

你也可以覆盖推断出的加载方式：

```js title="rspack.config.mjs"
export default {
  output: {
    wasmLoading: 'fetch',
  },
};
```

## output.wasmStreamingFallback

- **类型：** `boolean`
- **默认值：** `true`

控制生成的 WebAssembly 加载运行时代码是否在 `WebAssembly.compileStreaming` 或 `WebAssembly.instantiateStreaming` 因响应未使用 `application/wasm` MIME 类型而失败时，回退到非流式 API。

如果服务器始终以正确的 MIME 类型提供 WebAssembly 文件，可以将此选项设置为 `false`，从而省略相关的回退运行时代码。

```js title="rspack.config.mjs"
export default {
  output: {
    wasmStreamingFallback: false,
  },
};
```

## output.webassemblyModuleFilename

- **类型：** `string`
- **默认值：** `'[hash].module.wasm'`

指定 WebAssembly 模块的文件名。作为 `output.path` 目录下的相对路径。

```js title="rspack.config.mjs"
export default {
  output: {
    webassemblyModuleFilename: '[contenthash:8].wasm',
  },
};
```

:::tip
查看 [文件名占位符](/zh/config/filename-placeholders.md) 了解更多信息。
:::

## output.workerChunkLoading

- **类型：** `false | 'import-scripts' | 'require' | 'async-node' | 'import' | 'universal' | string`
- **默认值：** 根据 [`target`](/zh/config/target.md)、[`output.chunkFormat`](#outputchunkformat) 和 [`output.environment`](#outputenvironment) 推断。

控制 Worker 加载其他 JavaScript chunk 的方式，与控制 Worker 外部 chunk 加载方式的 [`output.chunkLoading`](#outputchunkloading) 分开配置。

例如，其他输出配置保持默认时：

| `target`                | `output.module` | 默认的 `output.workerChunkLoading` |
| ----------------------- | --------------- | ------------------------------- |
| `'web'` 或 `'webworker'` | `false`         | `'import-scripts'`              |
| `'node'`                | `false`         | `'require'`                     |
| `'async-node'`          | `false`         | `'async-node'`                  |
| `'web'`                 | `true`          | `'import'`                      |

对于 module 格式的 chunk，启用 `output.environment.dynamicImportInWorker` 时，Rspack 使用 `'import'`。支持动态导入的 ESM 输出可以为混合目标选择 `'universal'`。如果无法选择加载方式，则默认为 `false`。

可以显式禁用 Worker 的 chunk 加载：

```js title="rspack.config.mjs"
export default {
  output: {
    workerChunkLoading: false,
  },
};
```

## output.workerPublicPath

- **类型：** `string`
- **默认值：** `""`

为 Worker 设置一个公共路径，默认为 [output.publicPath](#outputpublicpath) 的值。只有在 Worker 脚本位于与其他脚本不同的路径时才使用此选项。

```js title="rspack.config.mjs"
export default {
  output: {
    workerPublicPath: '/workerPublicPath2/',
  },
};
```

## output.workerWasmLoading

- **类型：** `false | 'fetch' | 'async-node' | 'universal'`
- **默认值：** [`output.wasmLoading`](#outputwasmloading)

设置 Worker 内部的 WebAssembly 加载方式，默认继承 `output.wasmLoading`。

设为 `false` 可禁用 Worker 内部的 WebAssembly 加载：

```js title="rspack.config.mjs"
export default {
  output: {
    workerWasmLoading: false,
  },
};
```


本页改编自 [webpack 文档](https://webpack.docschina.org/configuration/output/)，遵循 [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)，且已作修改。

