小学社会311664 views
世界の国567837 views
中学理科1634014 views
中学英語814050 views
高校化学2934298 views
数学講師2917156 views
小学算数1204208 views
高校物理162938 views
いろは3027485 views
高校日本史191091 views
Help
Tools

English

CommonJS とは

CommonJS は Node.js で長年使われてきたモジュールシステムです。require() と module.exports を使用し、サーバーサイド JavaScript の標準として広く普及しました。

CommonJS の基本

CommonJS では、require() でモジュールを読み込み、module.exports で値をエクスポートします。

// math.js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

module.exports = { add, multiply };
// main.js
const math = require('./math.js');

console.log(math.add(2, 3));      // 5
console.log(math.multiply(2, 3)); // 6

エクスポートの書き方

CommonJS には複数のエクスポート方法があります。

// 方法1: module.exports に直接代入
module.exports = function greet(name) {
  return `Hello, ${name}!`;
};
// 方法2: module.exports にオブジェクトを代入
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b
};
// 方法3: exports のプロパティとして追加
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;

exports と module.exports の違い

exports は module.exports への参照です。注意が必要なのは、exports に直接代入しても意味がないことです。

// 動作しない
exports = { name: 'test' }; // module.exports は変更されない

// 正しい書き方
module.exports = { name: 'test' };
// または
exports.name = 'test';
exports.xxx = 値

module.exports にプロパティを追加。動作する。

exports = 値

参照を上書きするだけ。module.exports は変わらない。

require() の特徴

CommonJS の require() は同期的に動作します。

// 同期的にファイルを読み込む
const fs = require('fs');
const path = require('path');
const myModule = require('./myModule');

// require はどこでも使える
if (condition) {
  const extra = require('./extra');
}

Node.js の組み込みモジュール

Node.js には多くの組み込みモジュールがあり、CommonJS で読み込みます。

const fs = require('fs');
const path = require('path');
const http = require('http');
const crypto = require('crypto');

同期読み込みのメリットとデメリット

メリット

コードの実行順序が予測しやすい。シンプルな構文。どこでも require できる。

デメリット

ブラウザでは使えない(同期読み込みはネットワークをブロックする)。静的解析が難しく、Tree Shaking が効きにくい。

CommonJS の歴史

2009
CommonJS 誕生

サーバーサイド JavaScript のモジュール仕様として策定。

2009
Node.js 登場

CommonJS を採用し、サーバーサイド JavaScript の標準に。

2015
ES Modules 登場

ES2015 で公式のモジュール仕様として標準化。

現在
共存

Node.js で両方がサポートされ、徐々に ES Modules への移行が進む。

CommonJS は Node.js エコシステムで依然として広く使われていますが、ES Modules の普及に伴い、多くのプロジェクトが移行を進めています。