14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ESModules・CommonJSとは何か?

Last updated at Posted at 2023-03-19

概要

  • ESModulesは、ECMAScriptの仕様の一部。
  • CommonJSの一部の仕様として、Modulesがある。
  • ESModulesCommonJSは、文脈的にJavascript・TypeScriptで、別のモジュールを読み込むため仕組みを指すことが多い。
  • ESModuleCommonJSは、競合する関係。(正確には、ECMAScriptCommonJSは競合する関係)
    • ESModules
      • CommonJSの上位互換。
      • ESModuleからCommonJSのモジュールを読み込むことが可能。
    • CommonJS
      • Node.jsでデフォルトで採用されてきたが、最近はESModulesに変わりつつある。

実装上の違い

  • ESModules
    • モジュール側
      modules.mjs
      const getName = () => {
        return 'hoge';
      };
      const getAge = () => {
        return 18;
      };
      
      export {
        getName,
        getAge,
      };
      
    • モジュールを呼ぶ側
      index.mjs
      import { getAge } from './modules.mjs';
      console.log(getAge());
      
  • CommonJS
    • モジュール側
      modules.js
      module.exports = {
        getName: function() {
          return 'hoge';
        },
        getAge: function() {
          return 18;
        },
      }
      
    • モジュールを呼ぶ側
      index.js
      const { getAge } = require('./modules.js');
      console.log(getAge());
      

結論

  • ESModulesCommonJSはモジュールの仕様。
  • これからは、ESModulesが主流になる。
  • とは言え、まだCommonJSを使うことは多い。

ちなみに

  • ESModulesをブラウザで実行するには、type="module"の指定が必要。
    index.html
    <script type="module" src="./index.js">
    
14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?