Skip to main content

Mismatch in Module Imports between ES6 and CommonJS

JavaScript has a long history of different ways to handle modularizing code, this inconsistency has always been a pain in the ass for developers. Before ES6 was added to the JavaScript spec in 2015, CommonJS is the format which most modules on npm are delivered in. Now we are in the transition from CommonJS to ES6.

There is a mismatch in features between CommonJS and ES6 regarding the distinction between a default import and a module namespace object import.

ES6CommonJS
namespace importimport * as moment from "moment"const moment = require("moment")
default importimport moment from "moment"const moment = require("moment").default
warning

The ES6 modules spec states that a namespace import (import * as x) can only be an object, while CommonJS's require() allows for the import to be a function and be callable.

tip

TypeScript has a compiler flag to reduce the friction between the two different sets of constraints with esModuleInterop.