Transform ESM imports to CJS requires when the imported module is pure CJS.
npm install rolldown-plugin-require-cjs[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![Unit Test][unit-test-src]][unit-test-href]
Transform ESM imports to CJS requires when the imported module is pure CJS.
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
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.
``bash`
npm i rolldown-plugin-require-cjs
`tstrue
export interface Options {
include?: Array
exclude?: Array
order?: 'pre' | 'post' | undefined
/**
* A function to determine whether a module should be transformed.
* Return to force transformation, false to skip transformation,undefined
* or to let the plugin decide automatically.fs
*/
shouldTransform?: string[] | TransformFn
/**
* Whether to transform Node.js built-in modules (e.g., , path)process.getBuiltinModule()
* to calls, which has the best performance.process.getBuiltinModule
*
* Note: 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
`ts``
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
},
})
MIT License © 2025-PRESENT Kevin Deng
[npm-version-src]: https://img.shields.io/npm/v/rolldown-plugin-require-cjs.svg
[npm-version-href]: https://npmjs.com/package/rolldown-plugin-require-cjs
[npm-downloads-src]: https://img.shields.io/npm/dm/rolldown-plugin-require-cjs
[npm-downloads-href]: https://www.npmcharts.com/compare/rolldown-plugin-require-cjs?interval=30
[unit-test-src]: https://github.com/sxzz/rolldown-plugin-require-cjs/actions/workflows/unit-test.yml/badge.svg
[unit-test-href]: https://github.com/sxzz/rolldown-plugin-require-cjs/actions/workflows/unit-test.yml