LoginSignup
187
172

More than 5 years have passed since last update.

ES6の import / export

Last updated at Posted at 2016-04-25

結論

  • 基本的にはexport defaultを使う
  • 複数のモジュールをexportするときはexportを使う
  • 受け取り側はimportを使う

Default exports

1つのモジュールをexportする時。
こちらが推奨されている。

//------ myFunc.js ------
export default function () { ... };

//------ main1.js ------
import myFunc from 'myFunc';
myFunc();

classの場合は下記。

//------ MyClass.js ------
export default class { ... };

//------ main2.js ------
import MyClass from 'MyClass';
let inst = new MyClass();

export defaultexportdefaultという特殊な名前が付いたケースと同じこと。

import { default as foo } from 'lib';
import foo from 'lib';

Default exportsが推薦されている理由

David Hermanの言葉を引用。

ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

より簡潔な方がいいよねということ。

Named exports

複数のモジュールをexportする時。
個別に名前を付けてexportする。

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

こういう風にまとめても使える。

//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

参考

ECMAScript 6 modules: the final syntax

187
172
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
187
172