📂

ES Module(.js, .mjs)の読み込み方法まとめ

に公開

都度説明書くのがめんどくさいので記事を書きます

以降、以下のmodule.mjsが存在することを前提とします

module.mjs
const test = "Hello!";
export { test };

静的import宣言

MDN Web Docs

  • たぶん、こっちのほうがわかりやすいし書きやすい
  • 使用するにはそのソースファイル自体がモジュールとして読み込まれる必要がある
main.js
import { test } from "path/to/module.mjs";
console.log(test); // Expected Log Output: <string> "Hello!"

main.js側もモジュールである必要があり、scriptタグで読み込むならtype="module"の記述が必要です。

index.html
<script src="main.js" type="module"></script>

<!-- 下記のようにしてもOK -->
<script type="module">
    import { test } from "path/to/module.mjs";
    console.log(test); // Expected Log Output: <string> "Hello!"
</script>

Dynamic import (import())

MDN Web Docs

  • モジュールにしなくても使える
  • Promiseを返す関数なので何かしらの方法でPromiseを扱わないといけない
main.js
// Promise.prototype.then()を使う場合
import("path/to/module.mjs").then((module) => {
    const test = module.test;
    console.log(test); // Expected Log Output: <string> "Hello!"
});
main.js
// async/awaitを使う場合
(async () => {
    const module = await import("path/to/module.mjs");
    const test = module.test;
    console.log(test); // Expected Log Output: <string> "Hello!"
})();
main.js
// async/awaitを使う場合 (分割代入でもっと短く)
(async () => {
    const { test } = await import("path/to/module.mjs");
    console.log(test); // Expected Log Output: <string> "Hello!"
})();

import()Promiseを返す関数(のように振る舞うもの)なので、Top-level awaitとかasyncなIIFEとかPromise.prototype.then()とかで取り出してあげる必要があります。

Discussion