LoginSignup
0
0

More than 3 years have passed since last update.

JavaScript(ES6)のexportとimportについて調べてみた

Last updated at Posted at 2020-05-29

ES6で導入されたexportとimportについて調べた

注!完全に自分用の忘備録です。

<script type="module">が必須

import / export を使うにはscriptのtype属性に module の指定が必須です。
指定しないと以下のようなエラーになります。

Uncaught SyntaxError: Cannot use import statement outside a module

<script type="module">の実行タイミング

type="module"のスクリプトは最後に実行されます。
またDOM構築後に実行されるので、今までのようにheadタグに読み込むかbodyの閉じタグの上で読み込ませるか考える必要がありません。

実装例(その1)

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JSサンプル</title>
</head>
<body>
<script type="module" src="import.js"></script>
</body>
</html>
import.js
// 'module.js'でexportされたclassをimportする。
import { Point, Rectangle } from './module.js';

// importしたクラスを使用する。
const p = new Point(1, 2);
const r = new Rectangle(0, 0, 5, 5);
console.log(p.toString());
console.log(r.toString());
module.js
// classをexportしている。
export class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return `{x:${this.x}, y:${this.y}}`;
    }
}
export class Rectangle {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    toString() {
        return `{x:${this.x}, y:${this.y}, width:${this.width}, height:${this.height}}`;
    }
}

export defaultが推奨されている

特に理由がなければexportはdefaultが推奨されています。
参考:Default exports are favored

一旦まとめ

export、importの構文に振れる機会がそんなに多くなくてまだ完全に理解していないので、この記事は自分の理解度と共にアップデートしていく予定です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0