📂
ES Module(.js, .mjs)の読み込み方法まとめ
都度説明書くのがめんどくさいので記事を書きます
以降、以下のmodule.mjs
が存在することを前提とします
module.mjs
const test = "Hello!";
export { test };
import
宣言
静的
- たぶん、こっちのほうがわかりやすいし書きやすい
- 使用するにはそのソースファイル自体がモジュールとして読み込まれる必要がある
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>
import()
)
Dynamic import (
- モジュールにしなくても使える
- 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