包详细信息

rolldown-plugin-require-cjs

sxzz0MIT0.3.1

Transform ESM imports to CJS requires when the imported module is pure CJS.

自述文件

rolldown-plugin-require-cjs

npm version npm downloads Unit Test

Transform ESM imports to CJS requires when the imported module is pure CJS.

Why?

Some packages only provide CJS builds (e.g., typescript, @babel/parser), and importing them using ESM syntax increases Node's cjs-module-lexer overhead. This plugin converts ESM imports to CJS requires for such pure CJS packages, allowing Node to skip the cjs-module-lexer step and improve performance.

If performance is insignificant for your project, please do not use this plugin, as it introduces additional complexity and maintenance overhead.

See more: https://x.com/sanxiaozhizi/status/1968580207322808812

Appeal

We encourage the JavaScript ecosystem to continue its transition toward ESM. If you maintain a package that is still CJS-only, please consider offering an ESM build or migrating fully to ESM. Doing so will reduce reliance on plugins like this one and enhance the overall performance of the ecosystem.

Install

npm i rolldown-plugin-require-cjs

Options

export interface Options {
  include?: Array<string | RegExp> | string | RegExp
  exclude?: Array<string | RegExp> | string | RegExp
  order?: 'pre' | 'post' | undefined
  /**
   * A function to determine whether a module should be transformed.
   * Return `true` to force transformation, `false` to skip transformation,
   * or `undefined` to let the plugin decide automatically.
   */
  shouldTransform?: string[] | TransformFn
  /**
   * Whether to transform Node.js built-in modules (e.g., `fs`, `path`)
   * to `process.getBuiltinModule()` calls, which has the best performance.
   *
   * Note: `process.getBuiltinModule` is available since Node.js 20.16.0 and 22.3.0.
   */
  builtinNodeModules?: boolean
}

/**
 * @returns A boolean or a promise that resolves to a boolean,
 * or `undefined` to let the plugin decide automatically.
 */
export type TransformFn = (
  /**
   * The module ID (path) being imported.
   */
  id: string,
  /**
   * The module ID (path) of the importer.
   */
  importer: string,
) => Awaitable<boolean | undefined | void>

Example

RequireCJS({
  shouldTransform(id, importer) {
    // Force transformation for specific dependencies
    if (id === 'typescript') return true
    // Skip transformation for specific dependencies
    if (id === 'esm-only') return false
    // Auto-detect for other dependencies
    return undefined
  },
})

Sponsors

License

MIT License © 2025-PRESENT Kevin Deng