0Pricing
JavaScript Academy · レッスン

CommonJSの基礎 — require/module.exportsとexports

CommonJSのrequire()、module.exports、exportsのショートカットを学び、ESMとの小さな相互運用例も扱います。

「CommonJSの基礎 — require/module.exportsとexports」はCoddyKit上の無料JavaScript Academyレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはJavaScript Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 JavaScript Academyコースには全3レッスンが含まれています。

CJS:全体像

目標:小さなCommonJSモジュールを読んだり書いたりできるようにします。

  • require()でモジュールを読み込みます
  • module.exportsがエクスポートオブジェクトです
  • exportsは同じオブジェクトを指すショートカットです
  • ESMとの相互運用を簡単に確認します
CommonJSの基礎 — require/module.exportsとexports — イラスト1

require() — 考え方

CommonJSでは、require(path)がモジュールのエクスポートされたオブジェクトを返します。

// CommonJS import uses require()
const cjsExample = [
  "const math = require(\\"./math.js\\");",
  "console.log(math.sum(2, 3));"
];

console.log("require() example:");
for (const line of cjsExample) console.log(line);

// Emulate a loaded module object
const loaded = { sum: function (a, b) { return a + b; } };
console.log("emulated require sum:", loaded.sum(2, 3));
CommonJSの基礎 — require/module.exportsとexports — イラスト2

module.exports

module.exportsに値を代入すると、その値(関数、オブジェクトなど)をエクスポートできます。

// module.exports sets what the module returns
const lines1 = [
  "function greet(name) { return \\"Hi \\" + name; }",
  "module.exports = greet;"
];

console.log("module.exports example:");
for (const l of lines1) console.log(l);

// Emulate consumption
function greet(name) { return "Hi " + name; }
const api1 = greet; // like module.exports = greet
console.log("use exported fn:", api1("Ayla"));
CommonJSの基礎 — require/module.exportsとexports — イラスト3

exportsのショートカット

exports.prop = ...は問題ありません。ただし、exports = ...のように再代入してexportsを変更してはなりません。その場合、module.exportsを指さなくなるためです。

// exports is a shortcut to module.exports (same object)
const lines2 = [
  "// Good: add properties",
  "exports.sum = function (a, b) { return a + b; };",
  "",
  "// Pitfall: reassigning exports breaks the link",
  "exports = function () {}; // WRONG"
];

console.log("exports shortcut:");
for (const l of lines2) console.log(l);

// Emulate good usage
const moduleObj = {};
const exportsRef = moduleObj;  // like exports === module.exports initially
exportsRef.sum = function (a, b) { return a + b; };
console.log("sum via exportsRef:", moduleObj.sum(2, 4));
CommonJSの基礎 — require/module.exportsとexports — イラスト4

複数のエクスポート

多くの関数を格納したオブジェクトをエクスポートし、プロパティを使ってそれらを読み取ることができます。

// Export an object with multiple members
const lines3 = [
  "function add(a, b) { return a + b; }",
  "function mul(a, b) { return a * b; }",
  "module.exports = { add, mul };"
];

console.log("multiple exports object:");
for (const l of lines3) console.log(l);

// Emulate consumption
const api2 = {
  add: function (a, b) { return a + b; },
  mul: function (a, b) { return a * b; }
};
console.log("use add/mul:", api2.add(1, 2), api2.mul(2, 3));
CommonJSの基礎 — require/module.exportsとexports — イラスト5

ESM ↔ CJSの概要

相互運用(概要):

  • ESMからCJSをインポートすると、CJSのmodule.exportsをデフォルトとして受け取ることがよくあります。
  • 例:import pkg from "./cjs.js"とし、その後pkg.add()を使用します。
  • 例はシンプルに保ち、必要な場合を除いて1つのファイルでスタイルを混在させないようにします。
CommonJSの基礎 — require/module.exportsとexports — イラスト6

CJSエクスポート構文のクイズ

クイックチェック:CommonJSでのエクスポートです。

CommonJSの基礎 — require/module.exportsとexports — イラスト7

まとめ

まとめ:require()で読み込み、module.exportsでエクスポートし、exports.propでプロパティを追加します。exportsへの再代入は避けます。ESMとの相互運用では、CJSのmodule.exportsがデフォルトに割り当てられることがよくあります。

CommonJSの基礎 — require/module.exportsとexports — イラスト8

よくある質問

「CommonJSの基礎 — require/module.exportsとexports」レッスンは無料ですか?

はい。「CommonJSの基礎 — require/module.exportsとexports」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、JavaScript Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 JavaScript Academyコースには全3レッスンが含まれています。

「CommonJSの基礎 — require/module.exportsとexports」で何を学びますか?

CommonJSのrequire()、module.exports、exportsのショートカットを学び、ESMとの小さな相互運用例も扱います。 ブラウザで直接実行するハンズオンコードでJavaScript Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

JavaScript Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのJavaScript Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。

「CommonJSの基礎 — require/module.exportsとexports」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このJavaScript Academyレッスンでコードを書いて実行できますか?

はい。すべてのJavaScript Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ESMの基礎 — import/export、defaultとnamed
  2. CommonJSの基礎 — require/module.exportsとexports
  3. Nodeとブラウザのバンドラーにおけるモジュール解決
← JavaScript Academyに戻る