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

# Module parser

`module.parser` 用于控制 Rspack 如何解析不同类型的模块。它会影响依赖收集、`import.meta` 和动态 `import()` 等语法的识别，以及各类模块自己的解析行为。

## parser

- **类型：** `Object`
- **默认值：** `{}`

使用 `module.parser` 可以按模块类型配置解析器选项。

可配置的 parser 选项分组包括：

- `asset`: [Asset parser 选项](/zh/config/module-parser.md#asset)
- `javascript`, `javascript/auto`, `javascript/dynamic`, `javascript/esm`: [JavaScript parser 选项](/zh/config/module-parser.md#javascript)
- `json`: [JSON parser 选项](/zh/config/module-parser.md#json)
- `css`, `css/auto`, `css/global`, `css/module`: [CSS parser 选项](/zh/config/module-parser.md#cssauto)

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      // asset 模块的解析器选项
      asset: {
        dataUrlCondition: {
          maxSize: 16192,
        },
      },
      // javascript 模块的解析器选项
      javascript: {
        dynamicImportMode: 'lazy',
        dynamicImportPrefetch: false,
        dynamicImportPreload: false,
        url: true,
        importMeta: true,
      },
      // CSS 模块的解析器选项
      css: {
        namedExports: true,
      },
      // css/auto 模块的解析器选项
      'css/auto': {
        namedExports: true,
      },
      // css/module 模块的解析器选项
      'css/module': {
        namedExports: true,
      },
    },
  },
};
```

### asset

`asset` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      asset: {
        // options
      },
    },
  },
};
```

### asset.dataUrlCondition

- **类型：** `{ maxSize: number }`
- **默认值：** `{ maxSize: 8096 }`

如果当前模块的小于等于 `maxSize`，那么模块将被 Base64 编码，否则模块将会以文件形式被输出。该选项仅能作用于 [Asset modules](/zh/guide/features/asset-module.md)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      asset: {
        dataUrlCondition: {
          // 小于等于 4KB 的模块将被 Base64 编码
          maxSize: 4 * 1024,
        },
      },
    },
  },
};
```

### javascript

`javascript` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        // options
      },
    },
  },
};
```

### javascript.commonjsMagicComments


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



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

为 CommonJS 启用 [Magic comments](/zh/api/runtime-api/module-methods.md#magic-comments) 支持。

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

目前仅支持 `rspackIgnore` 和 `webpackIgnore` 注释。

:::tip
从 Rspack 2.1.0 开始，推荐使用 `rspackIgnore`。`webpackIgnore` 仍会被兼容支持。
:::

```js
const x = require(/* rspackIgnore: true */ 'x');
const y = require(/* webpackIgnore: true */ 'y');
```

### javascript.dynamicImportMode


- 类型： `'lazy' | 'eager' | 'weak' | 'lazy-once'`
- 默认值：`'lazy'`


指定动态导入的全局模式，详见 [`rspackMode`](/zh/api/runtime-api/module-methods.md#rspackmode)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        dynamicImportMode: 'eager',
      },
    },
  },
};
```

### javascript.dynamicImportPrefetch


- 类型： `boolean | number`
- 默认值：`false`


指定动态导入的全局 prefetch，详见 [`rspackPrefetch`](/zh/api/runtime-api/module-methods.md#rspackprefetch)。

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

### javascript.dynamicImportPreload


- 类型： `boolean | number`
- 默认值：`false`


指定动态导入的全局 preload，详见 [`rspackPreload`](/zh/api/runtime-api/module-methods.md#rspackpreload)。

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

### javascript.dynamicImportFetchPriority


- 类型： `'low' | 'high' | 'auto'`
- 默认值：`'auto'`


指定动态导入的全局 `fetchPriority`，详见 [`rspackFetchPriority`](/zh/api/runtime-api/module-methods.md#rspackfetchpriority)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        dynamicImportFetchPriority: 'high',
      },
    },
  },
};
```

### javascript.url


- 类型： `true | false | 'relative' | 'new-url-relative'`
- 默认值：`true`


启用 `new URL()` 语法解析。

- `true`：生成包含根 URL 的绝对 URL（默认行为）。
- `'relative'`：生成不包含根 URL 的相对 URL。
- `'new-url-relative'`：相对于公共路径的相对 URL。

当使用 `'new-url-relative'` 时，Rspack 将在编译时计算出相对于公共路径的相对 URL：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        url: 'new-url-relative',
      },
    },
  },
};
```

```js
new URL('./icon.svg', import.meta.url);

// 转换成 👇
new URL('./icon[hash].svg', import.meta.url);
```

当使用 `'relative'` 时，Rspack 将生成运行时代码，为 `new URL()` 语法计算出相对的 URL，结果 URL 中不包含根 URL：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        url: 'relative',
      },
    },
  },
};
```

```html
<!-- 使用 'relative' -->
<img src="icon.svg" />

<!-- 不使用 'relative' -->
<img src="file:///path/to/project/dist/icon.svg" />
```

### javascript.exprContextCritical


- 类型： `boolean | undefined`
- 默认值：`true`


启用完全动态依赖（`import(variable)`）的警告。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        exprContextCritical: false,
      },
    },
  },
};
```

### javascript.wrappedContextCritical


- 类型： `boolean | undefined`
- 默认值：`false`


启用部分动态依赖（`import("./path/to/" + variable)`）的警告。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        wrappedContextCritical: false,
      },
    },
  },
};
```

### javascript.unknownContextCritical


- 类型： `boolean | undefined`
- 默认值：`true`


在使用 `require` 函数时，如果无法进行静态分析（`require(variable)`），是否进行警告。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        unknownContextCritical: false,
      },
    },
  },
};
```

### javascript.wrappedContextRegExp


- 类型： `RegExp | undefined`
- 默认值：`/.*/`


设置正则表达式，用于匹配包裹的动态依赖。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        wrappedContextRegExp: /\.js$/,
      },
    },
  },
};
```

### javascript.importMeta

- **类型：** `boolean | 'preserve-unknown' | ImportMetaParserOptions`
- **默认值：** 当输出为 [ESM 格式](/zh/guide/features/esm.md) 时，默认值为 `'preserve-unknown'`，其他情况默认值为 `true`

用于控制是否要解析和替换源代码中的 `import.meta`，可选值有：

- `"preserve-unknown"`: [已知的 `import.meta` 字段](/zh/api/runtime-api/module-variables.md#import-meta) 会在编译期被替换，其他字段会被保留并在运行时被计算。
- `true`: 所有 `import.meta` 字段在编译期被替换。
- `false`: 所有 `import.meta` 字段都在运行时被计算。
- `ImportMetaParserOptions`: 对每个已知的 `import.meta` 字段分别配置。设置为 `false` 的字段会被保留并在运行时计算，未设置的字段会保持默认启用行为。未知的 `import.meta` 字段会被保留。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        importMeta: false,
      },
    },
  },
};
```

对象形式支持以下字段：

- 兼容 webpack 的字段：`dirname`、`filename`、`main`、`url`、`webpack` 和 `webpackContext`。
- Rspack 特有字段：`glob`、`resolve`、`rspackBaseUri`、`rspackHash`、`rspackInitSharing`、`rspackNonce`、`rspackPublicPath`、`rspackRsc`、`rspackShareScopes`、`rspackUniqueId` 和 `rspackVersion`。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        importMeta: {
          url: false,
          webpack: true,
          webpackContext: true,
          rspackHash: false,
        },
      },
    },
  },
};
```

`resolve` 只控制已经启用的 [`import.meta.resolve()`](#javascriptimportmetaresolve) 表达式是否在编译期处理。要使用 `import.meta.resolve()`，仍然需要启用 `javascript.importMetaResolve`。

### javascript.exportsPresence


- 类型： `'error' | 'warn' | 'auto' | false`
- 默认值：`'error'`


当使用了不存在的导出或存在冲突的重导出时，是否进行警告或报错。

- `"error"`：进行报错。
- `"warn"`：进行警告。
- `"auto"`：根据模块是否为严格 ESM，如果是严格 ESM 则报错，否则警告。
- `false`：关闭该功能。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        exportsPresence: 'auto',
      },
    },
  },
};
```

### javascript.importExportsPresence


- 类型： `'error' | 'warn' | 'auto' | false`


当使用了不存在的导出时，是否进行警告或报错。默认会遵循 [module.parser.javascript.exportsPresence](#javascriptexportspresence) 的配置。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        importExportsPresence: 'error',
      },
    },
  },
};
```

### javascript.reexportExportsPresence


- 类型： `'error' | 'warn' | 'auto' | false`


当使用了存在冲突的重导出时，是否进行警告或报错。默认会遵循 [module.parser.javascript.exportsPresence](#javascriptexportspresence) 的配置。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        reexportExportsPresence: 'error',
      },
    },
  },
};
```

### javascript.typeReexportsPresence


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

- **类型：** `'no-tolerant' | 'tolerant' | 'tolerant-no-check'`
- **默认值：** `'no-tolerant'`

是否宽容重导出类型的报错，常见有以下两种场景：

```ts
// case 1:
export { TypeA } from './types';
// case 2:
import { TypeB } from './types';
export { TypeB };
```

重导出类型时，由于 `TypeA`、`TypeB` 是类型，但使用在 `export {}` 值空间中，导致报错：

```txt
WARNING in ./re-exports.ts
  ⚠ ESModulesLinkingWarning: export 'TypeA' (reexported as 'TypeA') was not found in './types' (module has no exports)
   ╭─[2:0]
 1 │ // case 1:
 2 │ export { TypeA } from "./types";
   · ────────────────────────────────

WARNING in ./re-exports.ts
  ⚠ ESModulesLinkingWarning: export 'TypeB' (reexported as 'TypeB') was not found in './types' (module has no exports)
   ╭─[5:0]
 3 │ // case 2:
 4 │ import { TypeB } from "./types";
 5 │ export { TypeB };
   · ─────────────────
```

:::info 推荐配合 isolatedModules 使用 Rspack
使用 Rspack 打包 TypeScript 时，我们强烈推荐开启 tsconfig.json 中的 [isolatedModules](https://www.typescriptlang.org/tsconfig/#isolatedModules)（使用其他 bundler 时也推荐开启，因为这符合 bundler 如何编译 TypeScript：[.ts 文件之间相互独立，独立进行编译](/zh/guide/languages/typescript.md#%E5%BC%80%E5%90%AF-isolatedmodules)），此时对于重导出类型会收到 TypeScript 提示：`Re-exporting a type when 'isolatedModules' is enabled requires using 'export type'.`。
:::

- `'no-tolerant'`：默认行为，不会对重导出类型进行宽容处理，遇到上述情况会报错。
- `'tolerant'`：会对重导出类型进行宽容处理，同时检查子模块中是否有对应的类型导出，由于需要收集子模块中的类型导出信息，该配置需要和 builtin:swc-loader 的 [`collectTypeScriptInfo.typeExports`](/zh/guide/features/builtin-swc-loader.md#collecttypescriptinfotypeexports) 配合使用。
- `'tolerant-no-check'`：会对重导出类型进行宽容处理，但不会检查子模块中是否有对应的类型导出，此时可能存在误将本该报错的场景宽容掉（通常 IDE 也会有相应提示），由于不需要检查子模块，所以性能也会更好。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        typeReexportsPresence: 'tolerant',
      },
    },
    rules: [
      {
        test: /\.(?:js|mjs|ts)$/,
        use: [
          {
            loader: 'builtin:swc-loader',
            options: {
              detectSyntax: 'auto',
              collectTypeScriptInfo: {
                typeExports: true, // "tolerant" 模式下需开启 typeExports 收集
              },
            },
          },
        ],
      },
    ],
  },
};
```

详细示例可参考：[type reexports presence 示例](https://github.com/rstackjs/rstack-examples/tree/main/rspack/type-reexports-presence)

### javascript.worker


- 类型： `string[] | boolean | { alias?: string[], url?: 'new-url-relative' }`


为 Worker 解析提供自定义的语法，常用于支持 Worklet：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        worker: [
          // 支持 CSS paintWorklet
          'CSS.paintWorklet.addModule()',
          // 支持 AudioWorklet，最前面的 '*' 表示识别名为 'context' 的变量，比如：
          // let context = new AudioContext();
          // await context.audioWorklet.addModule(new URL("noise-processor.js", import.meta.url));
          '*context.audioWorklet.addModule()',
          // 继承默认语法：["Worker", "SharedWorker", "navigator.serviceWorker.register()", "Worker from worker_threads"]
          '...',
        ],
      },
    },
  },
};
```

`string[]` 写法等价于将相同的值配置到 `worker.alias`。
不配置 `worker.url` 时，Rspack 会保留已有的 Worker URL 输出。
当 `worker.url` 设置为 `'new-url-relative'` 且启用 `output.module` 时，
Rspack 会为 `new Worker(new URL(..., import.meta.url))` 输出静态的 `new URL()`
表达式。对于非 ESM 输出，Rspack 会保留已有的运行时 Worker URL 输出：

```js title="rspack.config.mjs"
export default {
  output: {
    module: true,
    chunkFilename: '[name].bundle.js',
  },
  module: {
    parser: {
      javascript: {
        worker: {
          url: 'new-url-relative',
        },
      },
    },
  },
};
```

```js
new Worker(new URL('./worker.js', import.meta.url));

// 将转换为 👇
new Worker(new URL('./worker.bundle.js', import.meta.url));
```

> 查看 [Web Workers](/zh/guide/features/web-workers.md) 了解更多。

### javascript.overrideStrict


- 类型： `'strict' | 'non-strict'`


将模块覆盖为严格模式或非严格模式。

这可能会影响模块的行为（某些行为在严格模式和非严格模式之间有所不同），因此请谨慎配置此选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        overrideStrict: 'strict',
      },
    },
  },
};
```

### javascript.commonjs


- 类型： `boolean | { exports?: boolean | 'skipInEsm' }`
- 默认值：`true`


控制 CommonJS 相关的解析行为。`true` 会保持 Rspack 对 CommonJS 导出赋值的默认转换；设置 `{ exports: 'skipInEsm' }` 时，当模块以 ESM 方式执行会跳过对应的重写，从而保留原始的运行时副作用；配置为 `false` 则关闭所有 CommonJS 导出处理。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        commonjs: {
          exports: 'skipInEsm',
        },
      },
    },
  },
};
```

### javascript.createRequire


- 类型： `boolean | string`
- 默认值：`false`


控制 Rspack 是否解析来自 Node.js `module` 的 `createRequire()`，并将创建出的 `require` 函数转换为可静态分析的依赖上下文。

当设置为 `true` 时，等价于 `"createRequire from module"`。对于这种默认形式，Rspack 会同时识别来自 `module` 和 `node:module` 的导入。

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

```js title="index.js"
import { createRequire as r } from 'module';

const require = r(import.meta.url);
const value = require('./value.cjs');
```

Rspack 也支持 namespace import 和 default import：

```js title="index.js"
import moduleDefault from 'module';
import * as moduleNs from 'node:module';

moduleDefault.createRequire(import.meta.url)('./value.cjs');
moduleNs.createRequire(import.meta.url)('./value.cjs');
```

`createRequire()` 的参数必须能被静态分析为 file URL 或绝对路径，例如 `import.meta.url`、`new URL('./dir/file.js', import.meta.url)` 或绝对 `file:` URL。当 `import.meta.url` 作为参数使用时，Rspack 会将其作为当前模块 URL 来计算 `createRequire` 的上下文。

你也可以使用 `"<specifier> from <module>"` 形式的字符串来自定义导入的 specifier 和模块来源：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        createRequire: 'createRequire from module',
      },
    },
  },
};
```

### javascript.requireAlias


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


控制是否解析和转换 CommonJS `require` 函数的重命名。

当设置为 `true` 时，Rspack 会解析和转换将 `require` 赋值给变量或作为参数传递的情况（例如：`const req = require; req('./module')`）。

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

### javascript.requireAsExpression


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


控制是否解析作为表达式使用的 `require`。

当设置为 `true` 时，Rspack 会解析作为表达式使用的 `require`（例如：`const req = require; req('./module')`）并发出警告。当设置为 `false` 时，这种模式会被忽略。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        requireAsExpression: false,
      },
    },
  },
};
```

### javascript.requireDynamic


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


控制是否解析动态 `require` 调用。

当设置为 `false` 时，Rspack 不会解析模块路径不是静态字符串的动态 `require` 调用（例如：`require(variable)`）。如果代码中不使用动态 require，可以提高构建性能。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        requireDynamic: false,
      },
    },
  },
};
```

### javascript.requireResolve


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


控制是否解析 `require.resolve()` 调用。

当设置为 `false` 时，Rspack 不会解析 `require.resolve()` 调用。如果代码中不使用 `require.resolve()`，可以提高构建性能。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        requireResolve: false,
      },
    },
  },
};
```

### javascript.importDynamic


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


控制是否解析动态 `import()` 调用。

当设置为 `false` 时，Rspack 不会解析模块路径不是静态字符串的动态 `import()` 调用（例如：`import(variable)`）。如果代码中不使用动态导入，可以提高构建性能。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        importDynamic: false,
      },
    },
  },
};
```

### javascript.strictThisContextOnImports


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


控制导入模块以对象调用方法的方式调用导出的函数时，Rspack 是否严格保留 `this` 绑定。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      javascript: {
        strictThisContextOnImports: false,
      },
    },
  },
};
```

这主要影响模块导出的函数中使用 `this` 来表示当前模块的场景，例如：

```js title="index.js"
import * as mod from './mod';

console.log(mod.fn());
```

```js title="mod.js"
export function fn() {
  return this.value;
}

export const value = 42;
```

上面的例子中，开启后会输出 `42`；关闭时为了获得更好的 tree shaking 优化，`value` 被视为未使用而被移除，结果变成 `undefined`。

- 设置为 `true` 时，Rspack 会更严格地遵循规范，优先保证运行时 `this` 语义正确，但会导致 tree shaking 优化效果下降。
- 设置为 `false` 时，Rspack 会生成更好的优化结果，但可能会导致运行时 `this` 语义不正确。

由于该用法在实际开发 ES 模块中非常少见，且开启会影响 tree shaking 优化效果，因此默认值为 `false`。

:::tip
如在实际开发时遇到该场景，建议优先避免使用该用法，如无法避免则建议使用 [module rule condition](/zh/config/module-rules.md#condition) 为指定模块单独配置。

```js title="rspack.config.mjs"
export default {
  module: {
    rules: [
      {
        test: /index\.js$/, // 仅为 index.js 模块中的导入语句启用 strictThisContextOnImports
        parser: {
          strictThisContextOnImports: true,
        },
      },
    ],
  },
};
```

:::

### javascript.jsx


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

Stability: Experimental


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


让 JavaScript 解析器能够识别 JSX 语法，这样语法解析和压缩等流程就可以在保留 JSX 的情况下继续工作。

当你在 loader 中将 JSX 的模式设置为 "preserve"，希望把 JSX 的转换留给后续工具（例如输出 JSX 的类库或依赖自定义 JSX runtime 的场景）时，可以开启该选项。

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

:::warning
该选项目前仅在 Rspack 中实验性提供，未来可能调整或移除。
:::

### javascript.importMetaResolve


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

Stability: Experimental


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


让 JavaScript 解析器能够解析 `import.meta.resolve()` 语法。

目前 `import.meta.resolve("./module")` 打包后的行为和 [`require.resolve("./module")`](/zh/api/runtime-api/module-methods.md#requireresolve) 类似，会将模块打包进最终的 bundle 中，并且返回该模块的模块 ID。

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

:::warning
该选项目前仅在 Rspack 中实验性提供，未来可能调整或移除。
:::

### javascript.pureFunctions


Stability: Experimental


- 类型： `string[]`


手动将命中模块中的顶层标识符标记为“调用无副作用”，供基于 pure function 的 tree shaking 使用。配置的名字必须能解析到该模块中的某个顶层名 —— 包括顶层的 function/class/变量声明、`import` 引入的标识符、`export { foo as bar }` 这类导出别名，以及匹配源模块默认导出（fn 或 arrow）时使用的 `default`。

这个选项主要面向无法直接修改源码的第三方库。你既可以将其配置在第三方库源文件上，也可以配置在消费侧文件上以断言对某个 import 的调用是 pure 的。

虽然这个选项定义在 `module.parser.javascript` 下，但在实际使用时通常更推荐通过 `module.rules[i].parser` 应用它，这样可以更细粒度地为特定模块配置 `pureFunctions`。

```js title="rspack.config.mjs"
export default {
  experiments: {
    pureFunctions: true,
  },
  module: {
    rules: [
      // 将第三方库中的导出标记为 pure
      {
        test: /node_modules\/some-library\/index\.js$/,
        parser: {
          pureFunctions: ['isString'],
        },
      },
      // 也可以在消费侧标记 import：该文件中对 `cva` 的调用都被视为 pure，
      // 不依赖库本身的声明。
      {
        test: /src\/styles\.js$/,
        parser: {
          pureFunctions: ['cva'],
        },
      },
    ],
  },
};
```

:::warning
该选项只有在启用 `experiments.pureFunctions` 时才会生效；该实验选项在生产模式下默认开启。如果在命中的模块中找不到对应的顶层绑定，Rspack 会发出警告。
:::

### \["javascript/auto"]

`javascript/auto` 模块的解析器选项，和 [`javascript` 的模块的解析器选项](#javascript)相同。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'javascript/auto': {
        // options
      },
    },
  },
};
```

### \["javascript/dynamic"]

`javascript/dynamic` 模块的解析器选项，和 [`javascript` 的模块的解析器选项](#javascript)相同。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'javascript/dynamic': {
        // options
      },
    },
  },
};
```

### \["javascript/esm"]

`javascript/esm` 模块的解析器选项，和 [`javascript` 的模块的解析器选项](#javascript)相同。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'javascript/esm': {
        // options
      },
    },
  },
};
```

### json

`json` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      json: {
        // options
      },
    },
  },
};
```

### json.exportsDepth

- **Type:** `number`
- **Default:** production 模式为 `Number.MAX_SAFE_INTEGER`, development 模式为 `1`

设置 Rspack 对于 `json` 模块导出的分析程度。development 模式下此项默认值为 `1`，可大幅提升构建效率。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      json: {
        // 例如，对于以下 json
        // {
        //   "depth_1": {
        //     "depth_2": {
        //       "depth_3": "foo"
        //     }
        //   },
        //   "_depth_1": "bar"
        // }
        // 当设置 exportsDepth: 1 时, `depth_2` and `depth_3` 将不会被分析。
        exportsDepth: 1,
      },
    },
  },
};
```

### json.parse

- **类型：** `(source: string) => any`
- **默认值：** `undefined`

自定义 Rspack 如何解析 `json` 模块的源码。该函数会收到模块源码字符串，函数必须返回可 JSON 序列化的数据。

Rspack 会先通过 `JSON.stringify` 序列化该函数的返回值，再将序列化后的 JSON 作为模块数据继续解析。普通 JSON 文件通常不需要配置这个选项；它主要用于将某些模块按 `type: 'json'` 处理，但又需要自定义源码到数据的转换逻辑。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      json: {
        parse: (source) => {
          return JSON.parse(source);
        },
      },
    },
  },
};
```

当命中的规则设置了 `type: 'json'` 时，也可以通过 `module.rules[].parser` 使用这个选项。例如，将 `.json5` 文件作为 JSON 模块解析：

```js title="rspack.config.mjs"
import JSON5 from 'json5';

export default {
  module: {
    rules: [
      {
        test: /\.json5$/,
        type: 'json',
        parser: {
          parse: JSON5.parse,
        },
      },
    ],
  },
};
```

### \["css/auto"]

`css/auto` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        // options
      },
    },
  },
};
```

### \["css/auto"].exportType

- **类型：** `'link' | 'text' | 'css-style-sheet' | 'style'`
- **默认值：** `'link'`

配置 CSS 内容如何导出到 JavaScript。

默认情况下，`exportType` 为 `'link'`，会将 CSS 作为样式表产物输出，并通过内置 CSS loading runtime 加载。

- `'link'`：将 CSS 作为样式表产物输出，并保留 CSS Modules 导出。
- `'text'`：将生成后的 CSS 文本作为默认导出。
- `'css-style-sheet'`：将 `CSSStyleSheet` 实例作为默认导出。
- `'style'`：在运行时通过 `<style>` 标签将生成后的 CSS 注入到文档中。

当使用 `exportType: 'text'` 或 `exportType: 'css-style-sheet'` 时，生成后的 CSS 会成为 JavaScript 模块的一部分，并且该模块不会额外输出独立 CSS 资源。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        exportType: 'text',
      },
    },
  },
};
```

### \["css/auto"].namedExports

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

使用 ES 模块命名导出来导出 CSS。

当使用 `namedExports: true` 时，你可以使用命名空间导出或命名导出：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        namedExports: true,
      },
    },
  },
};
```

```js
// 命名空间导出
import * as classes from './index.module.css';
// 命名导出
import { class1, class2 } from './index.module.css';
```

当使用 `namedExports: false` 时，除了命名空间导出和命名导出之外，还可以用默认导出：

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        namedExports: false,
      },
    },
  },
};
```

```js
// 命名空间导出
import * as classes from './index.module.css';
// 命名导出
import { class1, class2 } from './index.module.css';
// 默认导出
import classes from './index.module.css';
// 默认导出和命名导出
import classes, { class1, class2 } from './index.module.css';
```

### \["css/auto"].url

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

开启或者关闭对 CSS 中的 `url` 的处理。

当开启该选项 `url: true`, Rspack 将 `url` 函数中的路径解析成资源路径。
当关闭该选项 `url: false`, Rspack 忽略 `url` 函数，保持内容不变。

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

### \["css/auto"].resolveImport


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

- **类型：** `boolean | ((context: { url: string, media: string | undefined, resourcePath: string, supports: string | undefined, layer: string | undefined }) => boolean)`
- **默认值：** `true`

配置是否处理 `@import`。

- `true`: 启用所有 `@import` 规则的处理（默认）。
- `false`: 禁用所有 `@import` 规则的处理。
- `function`: 仅处理满足条件的 `@import` 规则。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        resolveImport: ({ url }) => {
          return url.includes('style.css');
        },
      },
    },
  },
};
```

### \["css/auto"].import

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

配置是否处理 CSS `@import` 规则。

- `true`: 解析并处理 `@import` 规则（默认）。
- `false`: 在生成的 CSS 中保留 `@import` 规则，不进行解析。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        import: true,
      },
    },
  },
};
```

### \["css/auto"].animation

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

启用或禁用对本地 `@keyframes` 标识符及其 `animation` 或 `animation-name` 使用处的重命名。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        animation: true,
      },
    },
  },
};
```

### \["css/auto"].customIdents

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

启用或禁用对自定义标识符的重命名，例如本地 `@counter-style` 和 `@font-palette-values` 名称。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        customIdents: true,
      },
    },
  },
};
```

### \["css/auto"].container

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

启用或禁用对本地 CSS container 名称及其使用处的重命名，例如 `container-name`、`container` 和 `@container`。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        container: true,
      },
    },
  },
};
```

### \["css/auto"].dashedIdents

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

启用或禁用对 dashed identifiers 的重命名，例如 CSS 自定义属性和 `@property` 声明。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        dashedIdents: true,
      },
    },
  },
};
```

### \["css/auto"].function

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

启用或禁用对本地 CSS function 名称及其使用处的重命名，例如 `@function --fn` 和 `--fn()`。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        function: true,
      },
    },
  },
};
```

### \["css/auto"].grid

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

启用或禁用对本地 CSS grid 线名和区域名及其使用处的重命名，例如 `grid-template-areas`、`grid-area` 和 `grid-row`。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        grid: true,
      },
    },
  },
};
```

### \["css/auto"].pure

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

为 CSS Modules 启用严格 pure 模式。启用后，CSS Module 中的每个选择器都必须至少包含一个本地 class 或 id 选择器。

对于 `css/auto`，该检查只会应用到被识别为 CSS Modules 的文件。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/auto': {
        pure: true,
      },
    },
  },
};
```

### css

`css` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      css: {
        // options
      },
    },
  },
};
```

### css.exportType

和 [`module.parser["css/auto"].exportType`](#cssautoexporttype) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      css: {
        exportType: 'text',
      },
    },
  },
};
```

### css.namedExports

和 [`module.parser["css/auto"].namedExports`](#cssautonamedexports) 一样。

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

### css.url

和 [`module.parser["css/auto"].url`](#cssautourl) 一样。

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

### css.resolveImport

参考 [`module.parser["css/auto"].resolveImport`](#cssautoresolveimport)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      css: {
        resolveImport: ({ url }) => {
          return url.includes('style.css');
        },
      },
    },
  },
};
```

### css.import

和 [`module.parser["css/auto"].import`](#cssautoimport) 一样。

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

### \["css/global"]

`css/global` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        // options
      },
    },
  },
};
```

### \["css/global"].exportType

和 [`module.parser["css/auto"].exportType`](#cssautoexporttype) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        exportType: 'style',
      },
    },
  },
};
```

### \["css/global"].namedExports

和 [`module.parser["css/auto"].namedExports`](#cssautonamedexports) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        namedExports: true,
      },
    },
  },
};
```

### \["css/global"].url

和 [`module.parser["css/auto"].url`](#cssautourl) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        url: true,
      },
    },
  },
};
```

### \["css/global"].resolveImport

参考 [`module.parser["css/auto"].resolveImport`](#cssautoresolveimport)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        resolveImport: ({ url }) => {
          return url.includes('style.css');
        },
      },
    },
  },
};
```

### \["css/global"].import

和 [`module.parser["css/auto"].import`](#cssautoimport) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        import: true,
      },
    },
  },
};
```

### \["css/global"].animation

和 [`module.parser["css/auto"].animation`](#cssautoanimation) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        animation: true,
      },
    },
  },
};
```

### \["css/global"].container

和 [`module.parser["css/auto"].container`](#cssautocontainer) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        container: true,
      },
    },
  },
};
```

### \["css/global"].customIdents

和 [`module.parser["css/auto"].customIdents`](#cssautocustomidents) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        customIdents: true,
      },
    },
  },
};
```

### \["css/global"].dashedIdents

和 [`module.parser["css/auto"].dashedIdents`](#cssautodashedidents) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        dashedIdents: true,
      },
    },
  },
};
```

### \["css/global"].function

和 [`module.parser["css/auto"].function`](#cssautofunction) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        function: true,
      },
    },
  },
};
```

### \["css/global"].grid

和 [`module.parser["css/auto"].grid`](#cssautogrid) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/global': {
        grid: true,
      },
    },
  },
};
```

### \["css/module"]

`css/module` 模块的解析器选项。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        // options
      },
    },
  },
};
```

### \["css/module"].exportType

和 [`module.parser["css/auto"].exportType`](#cssautoexporttype) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        exportType: 'css-style-sheet',
      },
    },
  },
};
```

### \["css/module"].namedExports

和 [`module.parser["css/auto"].namedExports`](#cssautonamedexports) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        namedExports: true,
      },
    },
  },
};
```

### \["css/module"].url

和 [`module.parser["css/auto"].url`](#cssautourl) 一样。

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

### \["css/module"].resolveImport

参考 [`module.parser["css/auto"].resolveImport`](#cssautoresolveimport)。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        resolveImport: ({ url }) => {
          return url.includes('style.css');
        },
      },
    },
  },
};
```

### \["css/module"].import

和 [`module.parser["css/auto"].import`](#cssautoimport) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        import: true,
      },
    },
  },
};
```

### \["css/module"].animation

和 [`module.parser["css/auto"].animation`](#cssautoanimation) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        animation: true,
      },
    },
  },
};
```

### \["css/module"].container

和 [`module.parser["css/auto"].container`](#cssautocontainer) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        container: true,
      },
    },
  },
};
```

### \["css/module"].customIdents

和 [`module.parser["css/auto"].customIdents`](#cssautocustomidents) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        customIdents: true,
      },
    },
  },
};
```

### \["css/module"].dashedIdents

和 [`module.parser["css/auto"].dashedIdents`](#cssautodashedidents) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        dashedIdents: true,
      },
    },
  },
};
```

### \["css/module"].function

和 [`module.parser["css/auto"].function`](#cssautofunction) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        function: true,
      },
    },
  },
};
```

### \["css/module"].grid

和 [`module.parser["css/auto"].grid`](#cssautogrid) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        grid: true,
      },
    },
  },
};
```

### \["css/module"].pure

和 [`module.parser["css/auto"].pure`](#cssautopure) 一样。

```js title="rspack.config.mjs"
export default {
  module: {
    parser: {
      'css/module': {
        pure: true,
      },
    },
  },
};
```


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

