元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

JavaScript:モジュールのawait

MDNのドキュメントからモジュールについて勉強しました。awaitはモジュール内で利用できる機能だそうです。詳しくは分かりませんが、モジュールが非同期関数として動作できるようになるそうです。

ファイル構造

  • index.html
  • main.js
  • modules/
    • square.js
    • circle.js
    • getColors.js
  • data/

ファイルの役割

  • index.html
    • main.jsの読み込み
  • main.js
    • モジュールの読み込み
  • square.js
    • 長方形に関するクラス
  • circle.js
    • 円に関するクラス
  • getColors.js
    • colors.jsonのデータの取得
  • colors.json
    • カラーコードをjson形式のデータに定義

モジュールのサンプルコード

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>モジュールの練習7</title>
    <script type="module" src="./main.js"></script>
</head>
<body>
    <button class="square">Square</button>
    <button class="circle">Circle</button>
</body>
</html>
/* main.js */
// awaitの例
import colors from './modules/getColors.js';

const squareBtn = document.querySelector('.square');
const circleBtn = document.querySelector('.circle');

//ボタンをクリックしたときの処理
squareBtn.addEventListener('click', () => {
    import('./modules/square.js').then((Module) => {
        let square = new Module.Square(10, 10, 100, 100, colors.blue);
        console.log(square.print());
    });
});

//ボタンをクリックしたときの処理
circleBtn.addEventListener('click', () => {
    import('./modules/circle.js').then((Module) => {
        let circle = new Module.Circle(0, 0, 100, colors.green);
        console.log(circle.print());
    });
});
/* getColors.js */
// fetch request
const colors = fetch('./data/colors.json')
    .then(response => response.json());

export default await colors;
{
    "yellow": "#F4D03F",
    "green": "#52BE80",
    "blue": "#5499C7",
    "red": "#CD6155",
    "orange": "#F39C12"
}
/* square.js */
// 長方形に関する変数や関数の定義
class Square{
    //コンストラクタ
    constructor(x, y, w, h, color){
        this.name = '長方形';
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.color = color;
    }

    print(){
        return `この${this.name}は、座標(${this.x}${this.y})、幅${this.w}、高さ${this.h}、色は${this.color}です。`;
    }
}

// クラスをエクスポートする
export { Square };
/* circle.js */
// 円に関する変数や関数の定義
class Circle{
    //コンストラクタ
    constructor(x, y, r, color){
        this.name = '円';
        this.x = x;
        this.y = y;
        this.r = r;
        this.color = color;
    }

    print(){
        return `この${this.name}は、座標(${this.x}${this.y})、半径${this.r}、色は${this.color}です。`;
    }
}

// クラスをエクスポートする
export { Circle };

実行結果

ボタンをクリックすると以下のようにコンソールに表示されます。

この長方形は、座標(10、10)、幅100、高さ100、色は#5499C7です。
この円は、座標(0、0)、半径100、色は#52BE80です。

参考

» HTML入門のまとめはこちらです。