Home

Awesome

Babel Transform: Node CommonJS to ES modules

Build Status

A Babel 7 compatible transform to convert Node-style CommonJS modules into the ES module specification. This was created specifically for an experimental module bundler, but has many uses outside of that initial use case. All major browsers have shipped support for ESM and Node currently has experimental support behind a flag. Babel offers a bridge to bring the old to the new, which is humorous given the origins of Babel which brought the new to the old. This module can reconcile differences as best as possible without resorting to hacks.

The goal of this transform is to produce spec-compliant code. Any behavior that diverges will throw by default. There are escape hatches however, if you know what they do.

This module will ignore existing ESM modules by default, so long as they do not reference the following globals: require, module.exports, or exports.

Notes

What to expect:

What not to expect:

Notable features not supported:

Notable features supported:

Usage

npm install --save-dev babel-plugin-transform-commonjs

Update your babel configuration:

{
  "plugins": ["transform-commonjs"]
}

Now code like this:

var { readFileSync } = require('path');
exports.readFileSync = readFileSync;

Will turn into this:

import { readFileSync as _readFileSync } from "path";
var module = {
  exports: {}
};
exports.readFileSync = _readFileSync;
export const readFileSync = _readFileSync;
export default module.exports;

Options