0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【今更シリーズ】CommonJSとES Modulesとは何?

Posted at

今更聞けない単語ですが、非常にわかりやすくまとめられた記事を見つけたので紹介。

以下、自分用メモ

CommonJS/ESModules(ESM) とは?

JavaScriptにおける、他ファイル(依存関係)を読み込む仕組み。
現在のスタンダードはESMだが、npmにはCommonJSで大量に作られた過去の資産があり、併用されることもある。

// CommonJS
const fs = require('fs');        // インポート
module.exports = myFunc;         // エクスポート
// require()、module.exportsまたはexportsを使ってたらCommonJS
// E Modules(ESM)
import fs from 'fs';
import { resdFile } from 'fs';

export default myFunc;
// import、exportを使ってたらESModules

CommonJSが登場する前の問題点

  1. スクリプトの分割管理が大変
    そもそもJavaScriptは、デフォルトで他ファイルを読み込むことができない。
    CommonJSもESMもない時代は、ブラウザでは<script src="...">を「読み込み順」に並べるしかなかった。
    (依存関係を考えて、適切な読み込み順を人間が考える必要があった)
  2. 名前衝突
    全ての変数・関数がglobalに置かれるので、名前の衝突リスクが高かった。
<script src="jquery.js"></script>
<script src="plugin.js"></script> <!-- jQueryの後に読み込む必要がある -->

CommonJSの登場

2009年に、サーバーサイドでのJavaScript実行環境Node.jsが登場した。それに伴い、モジュール機構としてCommonJSが作られ、広く普及した。

ESMの登場

2015年に、ECMAScript(国際団体が策定する標準仕様)がESModulesを公式しようとして定めた。
CommonJSは事実上の標準となっていたが、Node.jsが前提。具体的には、

  1. require()は「同期処理」なので、ネットワーク越しに読み込むブラウザには不向き
  2. require()は「関数呼び出し」なので、実行するまで依存関係がわからない

という問題があった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?