rollup-plugin-commonjs-named-exports
v2.0.0
Published
Re-export CommonJS named exports using Node.js cjs-module-lexer.
Maintainers
Readme
rollup-plugin-commonjs-named-exports
Re-export CommonJS named exports using Node.js cjs-module-lexer.
Useful to allow import { Fragment, useState } from "react"; (instead of forcing import React from "react";) instance for a bundled React as the source package still re-exports its CJS named exports based on process.env.NODE_ENV:
// react/index.js
if (process.env.NODE_ENV === "production") {
module.exports = require("./cjs/react.production.min.js");
} else {
module.exports = require("./cjs/react.development.js");
}
// react/cjs/react.development.js
// ...
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
// ...Based on esinstall and jspm-rollup.
Installation
npm install rollup-plugin-commonjs-named-exportsUsage
Rolldown
No additional plugins required — Rolldown handles CJS conversion natively.
Create a rolldown.config.js configuration file and import the plugin:
import commonjsNamedExports from "rollup-plugin-commonjs-named-exports";
export default {
input: "src/index.js",
output: {
dir: "output",
format: "es",
},
plugins: [commonjsNamedExports()],
};Rollup
@rollup/plugin-commonjs is still required for the actual CJS→ESM conversion. This plugin only provides the named export declarations on top.
Create a rollup.config.js configuration file and import the plugin:
import commonjs from "@rollup/plugin-commonjs";
import commonjsNamedExports from "rollup-plugin-commonjs-named-exports";
export default {
input: "src/index.js",
output: {
dir: "output",
},
plugins: [commonjs(), commonjsNamedExports()],
};Then call rollup either via the CLI or the API.
Caveats
- Static analysis only: named export detection relies on
cjs-module-lexer(the same lexer Node.js uses internally). Modules that assign exports entirely at runtime (e.g.module.exports[key] = valueinside a loop) will not have their named exports detected; only thedefaultexport will be available. - Entry points only: the plugin only wraps modules declared as bundle entry points. Non-entry CJS imports inside your source are not affected.
- ESM entries are passed through: if an entry has no statically detectable CJS exports the plugin is a no-op for that entry, leaving it to the bundler's default handling.
License
MIT. See license file.
