babel-plugin-transform-commonjs

raw JSON →
1.1.6 verified Sat Apr 25 auth: no javascript

A Babel 7 plugin that transforms CommonJS modules (require, module.exports, exports) into ES modules (import/export). Version 1.1.6 is the latest stable release. It aims to produce spec-compliant ESM code and throws on unsupported patterns like non-static require or require.extensions. It offers escape hatches (synchronousImport, exportsOnly) for controlled conversion. Unlike @babel/plugin-transform-modules-commonjs (which targets the opposite direction), this plugin converts CJS to ESM and is mainly used for building ESM-compatible bundles or migration.

error Error: [BABEL] unknown: You gave us a visitor for the node type "Expression" but it's not a valid type
cause Using an outdated version of @babel/core (<7) or incompatible Babel version.
fix
Install @babel/core@^7 and ensure @babel/core is in devDependencies.
error Module not found: Can't resolve 'path'
cause The plugin does not transform require calls for Node built-ins; bundler may fail if it expects a full ESM environment.
fix
Ensure bundler (e.g., webpack) polyfills Node core modules, or use a bundler that supports them natively.
breaking Non-static require calls (e.g., require(condition ? 'a' : 'b')) raise an exception by default.
fix Use 'synchronousImport: true' to convert non-static require to dynamic import (may produce invalid code outside bundler).
gotcha Invalid named exports (e.g., exports["I'mateapot"]) are not available as named exports; they only appear on default export.
fix Refactor exports to use valid identifiers or access via default export.
deprecated The option 'onlyExports' is documented but the code expects 'exportsOnly'. Check your Babel config.
fix Use 'exportsOnly' instead of 'onlyExports'.
npm install babel-plugin-transform-commonjs
yarn add babel-plugin-transform-commonjs
pnpm add babel-plugin-transform-commonjs

Installs the plugin, configures Babel, and transforms a CJS file with named exports.

npm install --save-dev babel-plugin-transform-commonjs @babel/core

echo '{
  "plugins": ["transform-commonjs"]
}' > .babelrc

echo 'var { readFileSync } = require("path");
exports.readFileSync = readFileSync;' > input.js

npx babel input.js