ESモジュール(ES Modules / ECMAScript Modules)を実装してみます。
ESモジュールを作成し、ブラウザで表示させてみます。
export
モジュールを作成します。
modules.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
export class Books { constructor(title, author) { this.title = title; this.author = author; } getContents() { return `タイトルは『${this.title}』で、著者は${this.author}です。`; } } export function getPublisher(publisher) { return `版元は${publisher}です。` } |
クラス、関数、変数等にexportキーワードを付与することによって外部に公開することが可能となります。exportが付与されていない場合は、外部から参照できません。
exportは下記のようにまとめることが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Books { constructor(title, author) { this.title = title; this.author = author; } getContents() { return `タイトルは『${this.title}』で、著者は${this.author}です。`; } } function getPublisher(publisher) { return `版元は${publisher}です。` } export { Books, getPublisher }; |
※exportする要素が一つだけの場合、defaultを指定することができます(後述)。
import モジュールのインポート
モジュールをインポートして利用します。
main.js
1 2 3 4 5 6 7 8 9 |
import { getPublisher, Books } from './module.js'; let publisher1 = getPublisher('新潮社'); let book1 = new Books('羅生門', '芥川龍之介'); let area = document.getElementById('area'); //タイトルは『羅生門』で、著者は芥川龍之介です。版元は新潮社です。 area.textContent = book1.getContents() + publisher1; |
import命令によってモジュールを取り込みます。※本記事ではブラウザで表示させるため、モジュールは / や ./ などのパス表記で記述し、拡張子を付ける必要があります。
exportの要素が一つでdefaultを指定した場合は、importの際に別の変数名を付けることが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 |
export default class Books { constructor(title, author) { this.title = title; this.author = author; } getContents() { return `タイトルは『${this.title}』で、著者は${this.author}です。`; } } |
1 2 3 4 5 6 7 8 |
import Mybook from './module.js'; let book1 = new Mybook('羅生門', '芥川龍之介'); let area = document.getElementById('area'); //タイトルは『羅生門』で、著者は芥川龍之介です。版元は新潮社です。 area.textContent = book1.getContents(); |
それぞれの要素をリネームすることもできます。
1 2 3 4 5 6 |
import {getPublisher as publish, Books as book} from './module.js'; let publisher1 = publish('新潮社'); let book1 = new book('羅生門', '芥川龍之介'); 〜省略 |
モジュール内の全ての要素を一括して取り込みます。
1 2 3 4 5 6 |
import * as module from './module.js'; let publisher1 = module.getPublisher('新潮社'); let book1 = new module.Books('羅生門', '芥川龍之介'); 〜省略 |
ブラウザ
ブラウザで表示させてみます。※Webサーバー上でのみ実行可です。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="module" src="./main.js"></script> </head> <body> <p id="area"></p> </body> </html> |
type属性にmoduleを指定します。利用できるブラウザは JavaScript modules via script tag をご参照下さい。
関連ページ