ES Modules / CommonJS Modules
January 12, 2022•119 words
ES Modules == ESM
CommonJS Modules == CJS
ESM では以下のようにモジュールを読み込める:
import { foo } from 'bar'
CJS の場合は:
const { foo } = require('foo')
両者の違い:
| ESM | CJS |
|---|---|
| ブラウザ互換 | Node.js |
| default で Strict | not Strict |
| Async | Sync |
Node.js で実行する場合、まず拡張子でどちらのモジュールシステムが使われているかが判定される :
// foo.cjs
console.log(typeof module); // object
// foo.mjs
console.log(typeof module); // undefined
あるいは package.json の type フィールドで指定も可能:
// package.json
{
...
"type": "commonjs"
...
}
// foo.js
console.log(typeof module);
➜ node foo.js
object
// package.json
{
...
"type": "commonjs"
...
}
// foo.js
console.log(typeof module);
➜ node foo.js
undefined