MDNのドキュメントからモジュールについて勉強しました。複数のモジュールで同じ変数名、関数名を使っていても問題ありません。インポート時に名前を変更できるので、変数名、関数名の衝突を回避できます。
ファイル構造
- index.html
- main.js
- modules/
- square.js
- circle.js
ファイルの役割
- index.html
- main.jsの読み込み
- main.js
- モジュールの読み込み
- square.js
- 長方形に関する変数と関数の定義
- circle.js
- 円に関する変数と関数の定義
モジュールのサンプルコード
square.jsとcircle.jsで、同じ変数名、関数名を定義します。インポート時にそれらの名前を変更します。
<!-- index.html --> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>モジュールの練習2</title> <script type="module" src="./main.js"></script> </head> <body></body> </html>
/* square.js */ // 長方形に関する変数や関数の定義 const name = "長方形"; let param = { x: 0, y: 0, w: 100, h: 100 }; function print(){ return `この${name}は、座標(${param.x}、${param.y})、幅${param.w}、高さ${param.h}です。`; } // 変数、関数、オブジェクトをエクスポートする export { name, param, print };
square.jsにname変数、paramオブジェクト、print()関数を定義しました。
/* circle.js */ // 円に関する変数や関数の定義 const name = "円"; let param = { x: 0, y: 0, r: 10 }; function print(){ return `この${name}は、座標(${param.x}、${param.y})、半径${param.r}です。`; } // 変数、関数、オブジェクトをエクスポートする export { name, param, print };
circle.jsにname変数、paramオブジェクト、print()関数を定義しました。
/* main.js */ // インポート時に名前を変更する(衝突回避) import { name as squareName, param as squareParam, print as squarePrint } from './modules/square.js'; import { name as circleName, param as circleParam, print as circlePrint } from './modules/circle.js'; console.log(squareName); console.log(squareParam); console.log(squarePrint()); console.log(circleName); console.log(circleParam); console.log(circlePrint());
インポート文が長くなるのでイマイチですが、名前の衝突は回避できます。
実行結果
ブラウザのコンソールに以下のように表示されます。
長方形 {x: 0, y: 0, w: 100, h: 100} この長方形は、座標(0、0)、幅100、高さ100です。 円 {x: 0, y: 0, r: 10} この円は、座標(0、0)、半径10です。