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.
Common errors
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.
Warnings
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'.
Install
npm install babel-plugin-transform-commonjs yarn add babel-plugin-transform-commonjs pnpm add babel-plugin-transform-commonjs Imports
- default export wrong
const plugin = require('babel-plugin-transform-commonjs'); const { default: plugin } = require('babel-plugin-transform-commonjs')correctimport plugin from 'babel-plugin-transform-commonjs' - plugin as object wrong
{ plugins: [require('babel-plugin-transform-commonjs')] }correct{ plugins: ['transform-commonjs'] } - options wrong
{ plugins: [['transform-commonjs', { onlyExports: true }]] }correct{ plugins: [['transform-commonjs', { synchronousImport: true, exportsOnly: true }]] }
Quickstart
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