← All tools

cjstoesm

Popularity 65 Updated Development & Build

A tool that can transform CommonJS to ESM

npmauto-collected

Installation

npm
npm install -g cjstoesm

Install with npm.

<div<img alt="Logo" src="https://raw.githubusercontent.com/wessberg/cjstoesm/master/documentation/asset/logo.png" height="150" /</div

A tool that can transform CommonJS to ESM

<a href="https://npmcharts.com/compare/cjstoesm?minimal=true"<img alt="Downloads per month" src="https://img.shields.io/npm/dm/cjstoesm.svg" /</a <a href="https://www.npmjs.com/package/cjstoesm"<img alt="NPM version" src="https://badge.fury.io/js/cjstoesm.svg" /</a <img alt="Dependencies" src="https://img.shields.io/librariesio/github/wessberg%2Fcjstoesm.svg" / <a href="https://github.com/wessberg/cjstoesm/graphs/contributors"<img alt="Contributors" src="https://img.shields.io/github/contributors/wessberg%2Fcjstoesm.svg" /</a <a href="https://github.com/prettier/prettier"<img alt="code style: prettier" src="https://img.shields.io/badge/codestyle-prettier-ff69b4.svg" /</a <a href="https://opensource.org/licenses/MIT"<img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /</a <a href="https://www.patreon.com/bePatron?u=11315442"<img alt="Support on Patreon" src="https://img.shields.io/badge/patreon-donate-green.svg" /</a

Description

This is a tool that converts CommonJS modules into tree-shakeable ES Modules. This allows you to not only bundle CommonJS modules for the browser, but also makes it possible for you to bundle them in modern tools such as Rollup.

It can also be used as a tool for migrating a CommonJS-based codebase to one based on ES-modules via a simple CLI.

cjstoesm can be used from the Command Line, as a JavaScript library, and as a TypeScript Custom Transformer.

Prior art such as babel-plugin-transform-commonjs and rollup-plugin-commonjs exists, but this Custom Transformer aims at producing code that is just as tree-shakeable as equivalent code written natively with ES Modules. Additionally, it aims to be as clean as possible, with no "wrappers" around modules as can be seen in other similar solutions.

For example, here's how cjstoesm may rewrite a CommonJS module:

Input

exports.foo = function foo() {};

Output

export function foo() {}

Here's another example:

Input

module.exports = {
  foo() {
    return 2 + 2;
  },
  bar: 3,
  baz: new RegExp("")
};

Output

export function foo() {
  return 2 + 2;
}
export const bar = 3;
export const baz = new RegExp("");
export default {foo, bar, baz};