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

# Output

The top-level output key contains a set of options instructing Rspack on how and where it should output your bundles, assets, and anything else you bundle or load with Rspack.

- **Type:** `Object`

## output.assetModuleFilename

- **Type:** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** `'[hash][ext][query]'`

The same as [`output.filename`](#outputfilename) but for [Asset Modules](/guide/features/asset-module.md).

`[name]`, `[file]`, `[query]`, `[fragment]`, `[base]`, and `[path]` are set to an empty string for the assets built from data URI replacements.

The name of the file to be output by the Asset module. This value can be overridden by [rules\[\].generator.filename](/config/module-rules.md#rulesgenerator).

:::info Asset module output as a separate file

- Module type is `'asset'` and asset is set to satisfy [rules\[\].parser.dataUrlCondition](/config/module-parser.md#assetdataurlcondition)
- Module type is `'asset/resource'`

:::

## output.asyncChunks

- **Type:** `boolean`
- **Default:** `true`

Controls whether dynamically imported modules are emitted as separate async chunks or bundled into existing chunks.

- `true`: Modules loaded via `import()` are split into independent async chunks. These chunks are emitted as separate files and are loaded on demand at runtime. This enables code splitting and keeps the initial bundle smaller.
- `false`: Dynamically imported modules are bundled into existing chunks instead of being emitted as separate files. No additional async chunk files are generated.

```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)

> In versions 1.x, use `experiments.rspackFuture.bundlerInfo` instead.

- **Type**:

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

Used to inject the currently used Rspack information into the generated asset:

- `version`: Used to specify the Rspack version, defaults to the `version` field in `@rspack/core/package.json`.
- `bundler`: Used to specify the name of the packaging tool, defaults to `rspack`.
- `force`: Whether to force the injection of Rspack information, which will be added to chunk as a runtime module, and defaults to `false`. An array can be used to select the items to be forced injected.

By default, injection occurs when either `import.meta.rspackVersion` or `import.meta.rspackUniqueId` is detected in the code, and only the corresponding runtime module is injected. Set `force` to `true` to always inject both:

- [`import.meta.rspackVersion`](/api/runtime-api/module-variables.md#importmetarspackversion): Inject version information.
- [`import.meta.rspackUniqueId`](/api/runtime-api/module-variables.md#importmetarspackuniqueid): Inject the unique ID of the bundler.

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

## output.chunkFilename

- **Type:** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** Determined by [`output.filename`](/config/output.md#outputfilename) when it is not a function, otherwise `'[id].js'`.

This option determines the name of non-initial chunk files. See [`output.filename`](/config/output.md#outputfilename) option for details on the possible values.

Note that these filenames need to be generated at runtime to send the requests for chunks. Because of this, placeholders like `[name]` and `[chunkhash]` need to add a mapping from chunk id to placeholder value to the output bundle with the Rspack runtime. This increases the size and may invalidate the bundle when placeholder value for any chunk changes.

When this option is omitted, Rspack derives it from [`output.filename`](#outputfilename):

- If `output.filename` is a string containing `[name]`, `[id]`, `[chunkhash]`, or `[contenthash]`, Rspack reuses that string. In particular, `[name]` is not replaced with `[id]`.
- Otherwise, Rspack inserts `[id].` before the basename, preserving the directory and query string.
- If `output.filename` is a function, the default is `'[id].js'`. Rspack does not call that function to derive `output.chunkFilename`.

| `output.filename`     | Default `output.chunkFilename` |
| --------------------- | ------------------------------ |
| `'[name].js'`         | `'[name].js'`                  |
| `'[name].mjs'`        | `'[name].mjs'`                 |
| `'scripts/bundle.js'` | `'scripts/[id].bundle.js'`     |
| A function            | `'[id].js'`                    |

To choose a different template explicitly:

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

:::tip
See [Filename placeholders](/config/filename-placeholders.md) for more information.
:::

Usage as a function:

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

## output.chunkFormat

- **Type:** `false | 'array-push' | 'commonjs' | 'module' | string`
- **Default:** Determined by [`target`](/config/target.md) and [`output.module`](#outputmodule)

The format of chunks (formats included by default are `'array-push'` (web/webworker), `'commonjs'` (node.js), `'module'` (ESM), but others might be added by plugins).

:::tip

The default value of this option depends on the [`target`](/config/target.md) and [`output.module`](#outputmodule) setting. For more details, search for "chunkFormat" [in the Rspack defaults](https://github.com/web-infra-dev/rspack/blob/main/packages/rspack/src/config/defaults.ts).

:::

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

## output.chunkLoading

- **Type:** `false | 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import' | string`

The method to load chunks (methods included by default are `'jsonp'` (web), `'import'` (ESM), `'import-scripts'` (webworker), `'require'` (sync node.js), `'async-node'` (async node.js), but others might be added by plugins). The default value will be determined based on the configuration of [`target`](/config/target.md) and [`chunkFormat`](#outputchunkformat).

:::tip

The default value of this option depends on the [`target`](/config/target.md) and [`chunkFormat`](#outputchunkformat) setting. For more details, search for `"chunkLoading"` [in the Rspack defaults](https://github.com/web-infra-dev/rspack/blob/main/packages/rspack/src/config/defaults.ts).

:::

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

## output.chunkLoadingGlobal

- **Type:** `string`
- **Default:** Determined by [`output.uniqueName`](/config/output.md#outputuniquename)

The global variable is used by Rspack for loading chunks.

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

## output.chunkLoadTimeout

- **Type:** `number`
- **Default:** `120000`

The Number of milliseconds before chunk request timed out.

```js title="rspack.config.mjs"
export default {
  output: {
    chunkLoadTimeout: 30000, // 30 seconds before chunk request timed out.
  },
};
```

## output.clean

- **Type:** `boolean | { keep?: string | RegExp | ((path: string) => boolean) }`
- **Default:** `false`

Remove files from the output directory before emitting assets. Set `clean` to `true` to enable cleaning:

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

To preserve a path, use `clean.keep`:

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

Alternatively, match paths with a regular expression:

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

For custom matching, return `true` from a function to keep a file:

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

## output.compareBeforeEmit

- **Type:** `boolean`
- **Default:** `true`

Tells Rspack to check if to be emitted file already exists and has the same content before writing to the output file system.

:::warning
Rspack will not write output file when file already exists on disk with the same content.
:::

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

## output.crossOriginLoading

- **Type:** `false | 'anonymous' | 'use-credentials'`
- **Default:** `false`

The `crossOriginLoading` config allows you to set the [crossorigin attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin) for dynamically loaded chunks.

If `target` is `'web'`, Rspack will dynamically create `<script>` and `<link>` tags to load asynchronous JavaScript and CSS resources. Rspack will add the `crossorigin` attribute to the `<script>` and `<link>` tags if the URLs of these resources are on other domains and `crossOriginLoading` is not `false`.

**Optional values**

`crossOriginLoading` has the following optional values:

- `false`: Do not set the [crossorigin attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin).
- `'anonymous'`: Set `crossorigin` to `'anonymous'` to enable cross-origin without user credentials.
- `'use-credentials'`: Set `crossorigin` to `'use-credentials'` enable cross-origin with user credentials.

**Example**

For example, set [output.publicPath](#outputpublicpath) to `https://example.com/` and `output.crossOriginLoading` to `'anonymous'`:

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

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

When Rspack dynamically loads JavaScript resources, it will generate the following HTML:

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

## output.cssChunkFilename

- **Type:** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** Determined by [`output.chunkFilename`](/config/output.md#outputchunkfilename) when it is not a function, otherwise `'[id].css'`.

This option determines the name of non-initial CSS output files on disk. See [`output.filename`](/config/output.md#outputfilename) option for details on the possible values.

For a string `output.chunkFilename`, Rspack replaces its `.js`, `.mjs`, or `.cjs` extension with `.css`, preserving any query string. For a function, the default is `'[id].css'`; the function is not called to derive the CSS filename.

You **must not** specify an absolute path here. However, feel free to include folders separated by `'/'`. This specified path combines with the [`output.path`](#outputpath) value to pinpoint the location on the disk.

## output.cssFilename

- **Type:** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** Derived from [`output.filename`](#outputfilename) when it is a string, otherwise `'[id].css'`.

This option determines the name of CSS output files on disk. See [`output.filename`](/config/output.md#outputfilename) option for details on the possible values.

For a string `output.filename`, Rspack replaces its `.js`, `.mjs`, or `.cjs` extension with `.css`, preserving any query string. If none of these extensions is present, the string is unchanged.

| `output.filename`        | Default `output.cssFilename` |
| ------------------------ | ---------------------------- |
| `'scripts/[name].js'`    | `'scripts/[name].css'`       |
| `'[name].mjs?version=1'` | `'[name].css?version=1'`     |
| A function               | `'[id].css'`                 |

When using a function for JavaScript filenames, configure CSS filenames separately if you need named CSS assets:

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

You **must not** specify an absolute path here. However, feel free to include folders separated by `'/'`. This specified path combines with the [`output.path`](#outputpath) value to pinpoint the location on the disk.

## output.devtoolFallbackModuleFilenameTemplate

- **Type:**

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

- **Default:** `undefined`

A fallback is used when the template string or function above yields duplicates.

See [`output.devtoolModuleFilenameTemplate`](/config/output.md#outputdevtoolmodulefilenametemplate).

## output.devtoolModuleFilenameTemplate

- **Type:**

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

- **Default:** `webpack://[namespace]/[resource-path]?[loaders]'`

This option is only used when [`devtool`](/config/devtool.md) uses an option that requires module names.

Customize the names used in each source map's `sources` array. This can be done by passing a template string or function. For example, when using `devtool: 'eval'`.

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

The following substitutions are available in template strings

| Template                  | Description                                                                                                           |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| \[absolute-resource-path] | The absolute filename                                                                                                 |
| \[relative-resource-path] | Resource path relative to the source map file’s directory, or to the emitted asset’s directory for inline source maps |
| \[all-loaders]            | Automatic and explicit loaders and params up to the name of the first loader                                          |
| \[hash]                   | The hash of the module identifier                                                                                     |
| \[id]                     | The module identifier                                                                                                 |
| \[loaders]                | Explicit loaders and params up to the name of the first loader                                                        |
| \[resource]               | The path used to resolve the file and any query params used on the first loader                                       |
| \[resource-path]          | The path used to resolve the file without any query params                                                            |
| \[namespace]              | The modules namespace. This is usually the library name when building as a library, empty otherwise                   |

When using a function, the same options are available camel-cased via the `info` parameter:

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

If multiple modules would result in the same name, [`output.devtoolFallbackModuleFilenameTemplate`](#outputdevtoolfallbackmodulefilenametemplate) is used instead for these modules.

## output.devtoolNamespace

- **Type:** `string`
- **Default:** [`output.uniqueName`](#outputuniquename)

This option determines the module's namespace used with the [`output.devtoolModuleFilenameTemplate`](#outputdevtoolmodulefilenametemplate). When not specified, it will default to the value of: [`output.uniqueName`](#outputuniquename). It's used to prevent source file path collisions in sourcemaps when loading multiple libraries built with Rspack.

For example, if you have 2 libraries, with namespaces `library1` and `library2`, which both have a file `./src/index.js` (with potentially different contents), they will expose these files as `webpack://library1/./src/index.js` and `webpack://library2/./src/index.js`.

## output.enabledChunkLoadingTypes

- **Type:** `('jsonp' | 'import-scripts' | 'require' | 'async-node' | string)[]`
- **Default:** Determined by [`output.chunkLoading`](#outputchunkloading), [`output.workerChunkLoading`](#outputworkerchunkloading) and Entry's chunkLoading config.

List of chunk loading types enabled for use by entry points. Will be automatically filled by Rspack. Only needed when using a function as entry option and returning chunkLoading option from there.

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

## output.enabledLibraryTypes

- **Type:** `string[]`
- **Default:** Determined by [output.library](#outputlibrary) and [Entry](/config/entry.md)

List of library types enabled for use by entry points.

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

## output.enabledWasmLoadingTypes

- **Type:** `('...' | 'fetch' | 'async-node' | 'universal')[]`
- **Default:** Determined by [`output.wasmLoading`](#outputwasmloading) and [`output.workerWasmLoading`](#outputworkerwasmloading)

List of Wasm loading types enabled for use by entry points.

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

## output.environment

- **Type:**

```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` specifies which ECMAScript language features and host environment capabilities Rspack is allowed to use when generating its runtime code.

This setting affects only code emitted by Rspack itself, such as runtime helpers. It does not downgrade your application source code.

### Default behavior

By default, `output.environment` is automatically inferred from your [target](/config/target.md) configuration.

Rspack evaluates `target` to determine which features your target environment supports. For example:

- If the target browsers support arrow functions, Rspack will use arrow functions in the runtime to produce more compact output.
- If `target` specifies a particular Node.js version, Rspack will infer the supported syntax from that version’s capabilities.

In general, you do not need to configure this option manually. You would override it only when you want to explicitly enforce or restrict specific features. Manual configuration replaces the inferred values and gives you direct control over the syntax used in the generated runtime.

### Example

Suppose `target` is set to `['web', 'es2018']`. In this case, Rspack will infer that `const` is supported and enable it by default. You can disable it by setting `output.environment.const: false`. Rspack will then emit runtime code that uses `var` declarations instead.

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

## output.filename

- **Type:** `string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** When [`output.module`](#outputmodule) is `true`, it is `'[name].mjs'`, otherwise it is `'[name].js'`.

This option determines the name of each output bundle. The bundle is written to the directory specified by the [`output.path`](#outputpath) option.

For a single [`entry`](/config/entry.md) point, this can be a static name.

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

However, when creating multiple bundles via more than one entry point, code splitting, or various plugins, you should use one of the following substitutions to give each bundle a unique name...

:::info Description of other cases where multiple bundles can be split

Rspack performs code splitting optimizations on user input code, which may include, but are not limited to, code splitting, bundle splitting, or splitting implemented through other plugins. These splitting actions can result in multiple bundles being generated, so the filenames of the bundles need to be generated dynamically.


:::

Use [Entry](/config/entry.md) name:

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

Using internal chunk id:

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

Using hashes generated from the generated content:

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

Combining multiple substitutions:

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

:::tip
See [Filename placeholders](/config/filename-placeholders.md) for more information.
:::

Using the function to return the filename:

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

Note this option is called filename but you are still allowed to use something like `'js/[name]/bundle.js'` to create a folder structure.

Note this option does not affect output files for on-demand-loaded chunks. It only affects output files that are initially loaded. For on-demand-loaded chunk files, the [`output.chunkFilename`](#outputchunkfilename) option is used. Files created by loaders also aren't affected. In this case, you would have to try the specific loader's available options.

## output.globalObject

- **Type:** `string`
- **Default:** Derived from [`target`](/config/target.md): `'global'` when the target provides `global`, otherwise `'globalThis'` when it supports `globalThis`, otherwise `'self'`.

When targeting a library, especially when `library.type` is `'umd'`, this option indicates what global object will be used to mount the library. To make UMD build available on both browsers and Node.js, set `output.globalObject` to `'this'`.

For example, when `output.globalObject` is omitted:

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

The return value of your entry point will be assigned to the global object using the value of `output.library.name`. Depending on the value of the `type` option, the global object could change respectively, e.g., `self`, `global`, or `globalThis`.

For example:

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

## output.hashDigest

- **Type:** `string`
- **Default:** `'hex'`

The encoding to use when generating the hash. Using `'base64'` for filenames might be problematic since it has the character `/` in its alphabet. Likewise `'latin1'` could contain any character.

## output.hashDigestLength

- **Type:** `number`
- **Default:** `16`

The prefix length of the hash digest to use, see [Hash length](/config/filename-placeholders.md#hash-length) for more details.

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

## output.hashFunction

- **Type:** `'md4' | 'xxhash64' | 'sha256'`
- **Default:** `'xxhash64'`

The hashing algorithm to use.

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

## output.hashSalt

- **Type:** `string`
- **Default:** `undefined`

An optional salt to update the hash.

## output.hotUpdateChunkFilename

- **Type:** `string`
- **Default:** When [`output.module`](#outputmodule) is `true`, it is `'[id].[fullhash].hot-update.mjs'`, otherwise it is `'[id].[fullhash].hot-update.js'`.

Customize the filenames of hot update chunks. See [`output.filename`](#outputfilename) option for details on the possible values.

The only placeholders allowed here are `[id]` and `[fullhash]`. For example:

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

:::tip
Typically you don't need to change `output.hotUpdateChunkFilename`.
:::

## output.hotUpdateGlobal

- **Type:** `string`
- **Default:** `"rspackHotUpdate" + output.uniqueName`

Only used when [`target`](/config/target.md) is set to `'web'`, which uses JSONP for loading hot updates.

A JSONP function is used to asynchronously load hot-update chunks.

For details see [`output.chunkLoadingGlobal`](#outputchunkloadingglobal).

## output.hotUpdateMainFilename

- **Type:** `string`
- **Default:** When [`output.module`](#outputmodule) is `true`, it is `'[runtime].[fullhash].hot-update.json.mjs'`, otherwise it is `'[runtime].[fullhash].hot-update.json'`.

Customize the main hot update filename. `[fullhash]` and `[runtime]` are available as placeholder.

:::tip
Typically you don't need to change `output.hotUpdateMainFilename`.
:::

## output.iife

- **Type:** `boolean`
- **Default:** `false` when [`output.module`](#outputmodule) is `true`, otherwise `true`.

Tells Rspack to add [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) wrapper around emitted code.

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

## output.importFunctionName

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

The name of the native `import()` function. Can be used for polyfilling, e.g. with [`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'`

The name of the native `import.meta` object (can be exchanged for a polyfill).

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

## output.library

Output a library exposing the exports of your entry point.

- **Type:** `string | string[] | object`

Let's take a look at an example.

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

Say you have exported a function in your `src/index.js` entry:

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

Now the variable `MyLibrary` will be bound with the exports of your entry file, and here's how to consume the Rspack bundled library:

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

In the above example, we're passing a single entry file to `entry`, however, Rspack can accept [many kinds of entry point](/config/entry.md), e.g., an `array`, or an `object`.

1. If you provide an `array` as the `entry` point, only the last one in the array will be exposed.

   ```js title="rspack.config.mjs"
   export default {
     entry: ['./src/a.js', './src/b.js'], // only exports in b.js will be exposed
     output: {
       library: 'MyLibrary',
     },
   };
   ```

2. If an `object` is provided as the `entry` point, all entries can be exposed using the `array` syntax of `library`:

   ```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
     },
   };
   ```

   Assuming that both `a.js` and `b.js` export a function `hello`, here's how to consume the libraries:

   ```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

- **Type:** `string`

Use a container(defined in global space) for calling `define`/`require` functions in an AMD module.

:::warning
Note that the value of `amdContainer` **must be** set as a global variable.
:::

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

Which will result in the following bundle:

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

### output.library.name

Specify a name for the library.

- **Type:** `string | string[] | {amd?: string, commonjs?: string, root?: string | string[]}`

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

### output.library.type

Configure how the library will be exposed.

- **Type:** `string`

  Types included by default are `'var'`, `'module'`, `'modern-module'`, `'system'`, `'assign'`, `'assign-properties'`, `'this'`, `'window'`, `'self'`, `'global'`, `'commonjs'`, `'commonjs2'`, `'commonjs-module'`, `'commonjs-static'`, `'amd'`, `'amd-require'`, `'umd'`, `'umd2'`, `'jsonp'`, but others might be added by plugins.

For the following examples, we'll use `_entry_return_` to indicate the values returned by the entry point.

#### Expose a variable

These options assign the return value of the entry point (e.g. whatever the entry point exported) to the name provided by [`output.library.name`](#outputlibraryname) at whatever scope the bundle was included at.

##### type: 'var'

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

When your library is loaded, the **return value of your entry point** will be assigned to a variable:

```js
var MyLibrary = _entry_return_;

// In a separate script with `MyLibrary` loaded…
MyLibrary.doSomething();
```

##### type: 'assign'

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

This will generate an implied global which has the potential to reassign an existing value (use with caution):

```js
MyLibrary = _entry_return_;
```

Be aware that if `MyLibrary` isn't defined earlier your library will be set in global scope.

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

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

Similar to [`type: 'assign'`](#type-assign) but a safer option as it will reuse `MyLibrary` if it already exists:

```js
// only create MyLibrary if it doesn't exist
MyLibrary = typeof MyLibrary === 'undefined' ? {} : MyLibrary;
// then copy the return value to MyLibrary
// similarly to what Object.assign does

// for instance, you export a `hello` function in your entry as follow
export function hello(name) {
  console.log(`Hello ${name}`);
}

// In another script with MyLibrary loaded
// you can run `hello` function like so
MyLibrary.hello('World');
```

#### Expose via object assignment

These options assign the return value of the entry point (e.g. whatever the entry point exported) to a specific object under the name defined by [`output.library.name`](#outputlibraryname).

##### type: 'this'

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

The **return value of your entry point** will be assigned to `this` under the property named by `output.library.name`. The meaning of `this` is up to you:

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

// In a separate script
this.MyLibrary.doSomething();
MyLibrary.doSomething(); // if `this` is window
```

##### type: 'window'

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

The **return value of your entry point** will be assigned to the `window` object using the `output.library.name` value.

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

window.MyLibrary.doSomething();
```

##### type: 'global'

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

The **return value of your entry point** will be assigned to the global object using the `output.library.name` value. Depending on the [`target`](/config/target.md) value, the global object could change respectively, e.g., `self`, `global` or `globalThis`.

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

global.MyLibrary.doSomething();
```

##### type: 'commonjs'

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

The **return value of your entry point** will be assigned to the `exports` object using the `output.library.name` value. As the name implies, this is used in CommonJS environments.

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

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

:::warning
Note that not setting a `output.library.name` will cause all properties returned by the entry point to be assigned to the given object; there are no checks against existing property names.
:::

#### Module definition systems

These options will result in a bundle that comes with a complete header to ensure compatibility with various module systems. The `output.library.name` option will take on a different meaning under the following `output.library.type` options.

##### type: 'module'

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // do not specify a `name` here
      type: 'module',
    },
  },
};
```

Output ES modules.

This is the more compatibility-oriented ESM library path: Rspack still uses the regular chunk / runtime rendering pipeline and then converts the entry exports into `export` statements. It fits simpler ESM library output, or cases where you mainly want webpack-style `module` semantics.

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

```js title="rspack.config.mjs"
export default {
  output: {
    library: {
      // do not specify a `name` here
      type: 'modern-module',
    },
  },
};
```

This configuration enables Rspack's dedicated rendering pipeline for ESM libraries. It emits direct `import` / `export` statements and supports library-oriented tree shaking, scope hoisting, code splitting, and [`output.library.preserveModules`](#outputlibrarypreservemodules).

:::tip `module` vs `modern-module`

- `module` stays on the regular chunk / runtime rendering pipeline and is closer to webpack-compatible ESM semantics.
- `modern-module` is handled by a dedicated ESM library plugin that owns chunk rendering, linking, scope hoisting, and splitChunks behavior, making it a better fit for publishable tree-shakable, code-split ESM libraries.
- `modern-module` currently exists as a separate type to fill the ESM library capability gap; once it is mature enough, the long-term direction is to converge it with `module` into a single `library.type`.
- `preserveModules` is only available with `modern-module`.
- When `output.library` is configured and `output.module = true`, Rspack currently defaults `output.library.type` to `modern-module` if you don't specify one explicitly.
- Do not mix `modern-module` with other library types in the same compilation, because it also changes chunk loading, chunk rendering, and scope-hoisting behavior.

:::

##### type: 'commonjs2'

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

The **return value of your entry point** will be assigned to the `module.exports`. As the name implies, this is used in Node.js (CommonJS) environments:

```js
module.exports = _entry_return_;

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

If we specify `output.library.name` with `type: commmonjs2`, the return value of your entry point will be assigned to the `module.exports.[output.library.name]`.

:::tip
Wondering the difference between CommonJS and CommonJS2 is? While they are similar, there are some subtle differences between them that are not usually relevant in the context of Rspack. (For further details, please [read this 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',
    },
  },
};
```

Individual exports will be set as properties on `module.exports`. The "static" in the name refers to the output being statically analysable, and thus named exports are importable into ESM via Node.js:

Input:

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

Output:

```js
function doSomething() {}

exports.doSomething = __webpack_exports__.doSomething;
```

Consumption (CommonJS):

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

Consumption (ESM):

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

:::tip
This is useful when source code is written in ESM and the output should be compatible with both CJS and ESM. For further details, please [read this issue](https://github.com/webpack/webpack/issues/14998) or [this article](https://dev.to/jakobjingleheimer/configuring-commonjs-es-modules-for-nodejs-12ed) (specifically, [this section](https://dev.to/jakobjingleheimer/configuring-commonjs-es-modules-for-nodejs-12ed#publish-only-a-cjs-distribution-with-property-exports)).
:::

:::tip How To Choose A CommonJS `library.type`

| Type              | Writes To           | Better Fit                                                                              |
| ----------------- | ------------------- | --------------------------------------------------------------------------------------- |
| `commonjs`        | `exports[...]`      | Compatibility with legacy configs that intentionally write to the `exports` object      |
| `commonjs2`       | `module.exports`    | General Node.js / CJS library output; the preferred choice for most new configs         |
| `commonjs-module` | `module.exports`    | Currently equivalent to `commonjs2`, mainly for historical webpack config compatibility |
| `commonjs-static` | `exports.foo = ...` | When you want Node.js ESM to be able to perform named imports from the CJS output       |

Rspack keeps these spellings primarily for webpack ecosystem compatibility and does not currently deprecate them at the config level. For new projects, prefer `commonjs2` or `commonjs-static` in most cases; reach for `commonjs` / `commonjs-module` mainly when migrating existing configs or when you explicitly need `exports` assignment semantics.

:::

##### type: 'amd'

This will expose your library as an AMD module.

AMD modules require that the entry chunk (e.g. the first script loaded by the `<script>` tag) be defined with specific properties, such as to `define` and `require` which is typically provided by RequireJS or any compatible loaders (such as almond). Otherwise, loading the resulting AMD bundle directly will result in an error like `define is not defined`.

With the following configuration:

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

The generated output will be defined with the name `"MyLibrary"`, i.e.:

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

The bundle can be included as part of a script tag, and the bundle can be invoked like so:

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

If `output.library.name` is undefined, the following is generated instead.

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

This bundle will not work as expected, or not work at all (in the case of the almond loader) if loaded directly with a `<script>` tag. It will only work through a RequireJS compatible asynchronous module loader through the actual path to that file, so in this case, the `output.path` and `output.filename` may become important for this particular setup if these are exposed directly on the server.

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

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

This packages your output with an immediately executed AMD `require(dependencies, factory)` wrapper.

The `'amd-require'` type allows for the use of AMD dependencies without needing a separate later invocation. As with the `'amd'` type, this depends on the appropriate [`require` function](https://github.com/amdjs/amdjs-api/blob/master/require.md) being available in the environment in which the Rspack output is loaded.

With this type, the library name can't be used.

##### type: 'umd'

This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD, and as global variable. Take a look at the [UMD Repository](https://github.com/umdjs/umd) to learn more.

In this case, you need the `library.name` property to name your module:

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

And finally the output is:

```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_;
});
```

Note that omitting `library.name` will result in the assignment of all properties returned by the entry point be assigned directly to the root object, as documented under the [object assignment section](#expose-via-object-assignment). Example:

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

The output will be:

```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_;
});
```

You may specify an object for `library.name` for differing names per targets:

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

##### type: 'system'

This will expose your library as a [`System.register`](https://github.com/systemjs/systemjs/blob/master/docs/system-register.md) module.

System modules require that a global variable `System` is present in the browser when the Rspack bundle is executed. Compiling to `System.register` format allows you to `System.import('/bundle.js')` without additional configuration and has your Rspack bundle loaded into the System module registry.

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

Output:

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

By adding `output.library.name` to configuration in addition to having `output.library.type` set to `system`, the output bundle will have the library name as an argument to `System.register`:

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

#### Other types

**type: 'jsonp'**

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

This will wrap the return value of your entry point into a jsonp wrapper.

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

The dependencies for your library will be defined by the [`externals`](/config/externals.md) config.

### output.library.export

Specify which export should be exposed as a library.

- **Type:** `string | string[]`
- **Default:** `undefined`

It is `undefined` by default, which will export the whole (namespace) object. The examples below demonstrate the effect of this configuration when using [`output.library.type: 'var'`](#type-var).

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

The default export of your entry point will be assigned to the library name:

```js
// If your library has a default export
var MyLibrary = _entry_return_.default;
```

You can pass an array to `output.library.export` as well, it will be interpreted as a path to a module to be assigned to the library name:

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

And here's the library code:

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

### output.library.auxiliaryComment

Add a comment in the UMD wrapper.

- **Type:** `string | { amd?: string, commonjs?: string, commonjs2?: string, root?: string }`
- **Default:** `undefined`

To insert the same comment for each `umd` type, set `auxiliaryComment` to a string:

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

which will yield the following:

```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_;
});
```

For fine-grained control, pass an object:

```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

- **Type:** `boolean`
- **Default:** `undefined`

When using `output.library.type: "umd"`, setting `output.library.umdNamedDefine` to `true` will name the AMD module of the UMD build. Otherwise, an anonymous `define` is used.

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

The AMD module will be:

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

### output.library.preserveModules

- **Type:** `string`
- **Default:** `undefined`

:::info
Only available when `library.type` is set to `modern-module`.
:::

When enabled, Rspack will preserve the original directory structure of modules within the specified directory. Each module will be emitted as a separate file, maintaining the same relative path as the source.

`preserveModules` is a special form of bundling — it can be thought of as **bundle + splitChunks where each module gets its own chunk**. Unlike a bundleless tool, Rspack still applies its full bundling pipeline (tree shaking, scope hoisting, minification, etc.), but splits the output so that each module in the specified directory becomes its own output file.

:::warning
**Barrel files may not be emitted or exposed as you expect.** Since `preserveModules` is still a form of bundling, Rspack only emits modules that are reachable from the configured entries. Non-entry barrel files (for example, an `index.ts` that re-exports from other modules) can still be emitted with their re-exports if they are part of the module graph, but only the configured entry exports are exposed through the main library entry. Unused barrel re-exports may be tree-shaken, and a barrel file may not be emitted at all if nothing references it. If you need to expose exports from a barrel file via your library entry, configure it as an entry point.
:::

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

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

## output.module

- **Type:** `boolean`
- **Default:** `false`

Output JavaScript files as module type.

When enabled, [`output.iife`](#outputiife) defaults to `false` and [`output.scriptType`](#outputscripttype) defaults to `'module'`. Explicit values for these options take precedence over the defaults.

If you set [`output.library.type`](#outputlibrarytype) to 'module' or 'modern-module', Rspack will set `output.module` to `true` for you automatically.

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

## output.path

- **Type:** `string`
- **Default:** `path.resolve(process.cwd(), 'dist')`

The output directory as an **absolute** path.


**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'),
  },
};
```


Note that `[fullhash]` in this parameter will be replaced with a hash of the compilation.

:::warning

- The path must not contain an exclamation mark (`!`) as it is reserved by Rspack for loader syntax.
- Relative paths are resolved against `context`.

:::

## output.pathinfo

- **Type:** `boolean | 'verbose'`
- **Default:** `false`

Controls whether Rspack adds module-related comments to the generated bundle. These comments are useful for debugging, inspecting build output, and understanding tree-shaking behavior.

- `true`: Enables basic comments, including module path information.
- `false`: Disables all comments, which is the default behavior.
- `'verbose'`: Outputs detailed comments, such as module exports, runtime details, tree-shaking information, and bailout reasons. This mode is helpful when diagnosing build issues or performing in-depth bundle analysis.

For example, enabling `pathinfo`:

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

The generated bundle will contain comments like:

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

:::warning
`pathinfo` is primarily intended for development and debugging. These comments increase bundle size and may expose details about your source structure. Avoid using it in production.
:::

## output.publicPath

- **Type:** `'auto' | string | ((pathData: PathData, assetInfo?: AssetInfo) => string)`
- **Default:** `'auto'` when the [target](/config/target.md) supports `document` or `importScripts`, otherwise `''`.

Set the base URL path prefix for bundled static assets (such as JS, CSS, images, etc.).

For example, `'web'` and `'webworker'` targets default to `'auto'`, while `'node'` defaults to an empty string. With an empty string, asset URLs have no additional prefix.

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

See [Asset base path](/guide/features/asset-base-path.md) for more details.

## output.scriptType

- **Type:** `false | 'text/javascript' | 'module'`
- **Default:** `false`

This option allows loading asynchronous chunks with a custom script type, such as `<script type="module" ...>`.

:::tip
If [`output.module`](#outputmodule) is set to `true`, `output.scriptType` will default to `'module'` instead of `false`.
:::

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

## output.sourceMapFilename

- **Type:** `string`
- **Default:** `'[file].map[query]'`

Configure how source maps are named. Only takes effect when [`devtool`](/config/devtool.md) is set to `'source-map'`, which writes an output file.

The `[name]`, `[id]`, `[fullhash]` and `[chunkhash]` substitutions from [`output.filename`](#outputfilename) can be used. In addition to those, you can use substitutions listed under Filename-level in [Filename placeholders](/config/filename-placeholders.md).

## output.strictModuleErrorHandling

- **Type:** `boolean`
- **Default:** `false`

Handle error in module loading as per ECMAScript Modules spec at a performance cost.

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

## output.strictModuleExceptionHandling

- **Types:** boolean

Tell Rspack to remove a module from the module instance cache (require.cache) if it throws an exception when it is required.

## output.trustedTypes

- **Type:** `true | string | object`
- **Default:** `undefined`

Controls [Trusted Types](https://web.dev/trusted-types) compatibility. When enabled, Rspack will detect Trusted Types support and, if they are supported, use Trusted Types policies to create script URLs it loads dynamically. Use when the application runs under a [`require-trusted-types-for`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) Content Security Policy directive.

It is disabled by default (no compatibility, script URLs are strings). Set it to `true` to enable Trusted Types with a policy name derived from [`output.uniqueName`](#outputuniquename).

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

### output.trustedTypes.policyName

- **Type:** `string`
- **Default:** Derived from [`output.uniqueName`](#outputuniquename)

The name of the Trusted Types policy created by Rspack to serve bundle chunks. Use this option when the policy name must match a CSP `trusted-types` allowlist.

If `policyName` is omitted, Rspack derives it from [`output.uniqueName`](#outputuniquename), replacing unsupported characters with `_`. If the derived name is empty, it falls back to `'rspack'`. The string shorthand `trustedTypes: 'my-policy'` is equivalent to setting `trustedTypes.policyName`.

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

### output.trustedTypes.onPolicyCreationFailure

- **Type:** `"stop" | "continue"`
- **Default:** `"stop"`

Determine whether to proceed with loading in anticipation that [`require-trusted-types-for 'script'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) has not been enforced or to immediately fail when the call to `trustedTypes.createPolicy(...)` fails due to the policy name being absent from the CSP `trusted-types` list or being a duplicate.

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

## output.uniqueName

- **Type:** `string`
- **Default:** Derived in the following priority order:
  1. The `name` of [`output.library`](#outputlibrary)
  2. The `name` field in `package.json` under the `context` directory
  3. `''` (empty string)

This option is used to identify a unique name for the current build. It mainly helps prevent runtime code conflicts when multiple Rspack applications run in the same global environment.

`output.uniqueName` affects the default values of the following options:

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

To override the default value:

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

## output.wasmLoading

- **Type:** `false | 'fetch' | 'async-node' | 'universal'`
- **Default:** Derived from [`target`](/config/target.md), [`output.module`](#outputmodule), and [`output.environment`](#outputenvironment).

Selects the method used to load WebAssembly modules. Set it to `false` to disable WebAssembly loading.

Rspack chooses `'fetch'` when the target supports fetching WebAssembly, or `'async-node'` when it provides Node.js built-ins. For mixed targets where these capabilities differ, ESM output with dynamic import support can use `'universal'`. If no method can be selected, the default is `false`.

Examples with otherwise default output settings:

| `target`                                                    | `output.module` | Default `output.wasmLoading` |
| ----------------------------------------------------------- | --------------- | ---------------------------- |
| `'web'` or `'webworker'`                                    | `false`         | `'fetch'`                    |
| `'electron-renderer'`                                       | `false`         | `'fetch'`                    |
| `'node'` or `'async-node'`                                  | `false`         | `'async-node'`               |
| `'electron-main'`, `'electron-preload'`, or `'node-webkit'` | `false`         | `'async-node'`               |
| `['web', 'node']`                                           | `true`          | `'universal'`                |

To override the inferred method:

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

## output.wasmStreamingFallback

- **Type:** `boolean`
- **Default:** `true`

Controls whether the generated WebAssembly loading runtime falls back to a non-streaming API when `WebAssembly.compileStreaming` or `WebAssembly.instantiateStreaming` rejects because the response does not use the `application/wasm` MIME type.

Set this option to `false` to omit the fallback runtime code when your server always serves WebAssembly files with the correct MIME type.

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

## output.webassemblyModuleFilename

- **Type:** `string`
- **Default:** `'[hash].module.wasm'`

Specifies the filename of WebAssembly modules. It should be provided as a relative path within the `output.path` directory

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

:::tip
See [Filename placeholders](/config/filename-placeholders.md) for more information.
:::

## output.workerChunkLoading

- **Type:** `false | 'import-scripts' | 'require' | 'async-node' | 'import' | 'universal' | string`
- **Default:** Derived from [`target`](/config/target.md), [`output.chunkFormat`](#outputchunkformat), and [`output.environment`](#outputenvironment).

Controls how workers load additional JavaScript chunks. This is separate from [`output.chunkLoading`](#outputchunkloading), which controls chunk loading outside workers.

For example, with otherwise default output settings:

| `target`                 | `output.module` | Default `output.workerChunkLoading` |
| ------------------------ | --------------- | ----------------------------------- |
| `'web'` or `'webworker'` | `false`         | `'import-scripts'`                  |
| `'node'`                 | `false`         | `'require'`                         |
| `'async-node'`           | `false`         | `'async-node'`                      |
| `'web'`                  | `true`          | `'import'`                          |

For module-format chunks, Rspack uses `'import'` when `output.environment.dynamicImportInWorker` is enabled. Mixed targets can use `'universal'` with ESM output and dynamic import support. If no loading method can be selected, the default is `false`.

To disable worker chunk loading explicitly:

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

## output.workerPublicPath

- **Type:** `string`
- **Default:** `""`

Set a public path for Worker, defaults to value of [output.publicPath](#outputpublicpath). Only use this option if your worker scripts are located in a different path from your other scripts.

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

## output.workerWasmLoading

- **Type:** `false | 'fetch' | 'async-node' | 'universal'`
- **Default:** [`output.wasmLoading`](#outputwasmloading)

Sets how workers load WebAssembly modules. Defaults to `output.wasmLoading`.

Set to `false` to disable WebAssembly loading inside workers:

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


This page is adapted from [webpack documentation](https://webpack.js.org/configuration/output/) under the [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), with modifications.

