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 introduced ESM in 2015, CommonJS is the format which most modules on npm are delivered in. Now we are in the transition from CommonJS to ESM.
There is a mismatch in features between CommonJS and ES6 regarding the distinction between a module namespace object import and a default import.
| ES6 | CommonJS | |
|---|---|---|
| namespace import | import * as moment from "moment" | const moment = require("moment") |
| default import | import moment from "moment" | const moment = require("moment").default |
注意
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.
提示
TypeScript has a compiler flag to reduce the friction between the two different sets of constraints with esModuleInterop.