1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初心者による ES6 export/import

Last updated at Posted at 2020-01-17

概要

アプリの規模が大きくなるほど、アプリを機能ごとに分割/整理するモジュールの存在はますます重要になってくる。

基本的な書き方

sample.js
import { name, ...} from module
 //name : インポートする要素
 //module : モジュール(拡張子はつけない)

export class XXX { }

がexport/importの基本的な書き方である。外部からアクセスできる要素にのみexportキーワードをつける。たとえば、

sample1.js
const name = 'Satou Shio'

export class Member {
 //コード
}

export class Class {
 //コード
}
sample2.js
import { Member, Class } from './sample1'

let member = new Member('佐藤')
console.log(member.getName())

import命令の様々な記法

importには、様々な書き方がある。

1. モジュール全体をまとめてインポート

アスタリスク(*)でモジュール内のすべての要素をインポートできる。この場合、asキーワードでモジュール名を別途指定しておく必要があります。

sample.js
import * as app from './sample1'

let member = new app.Member('佐藤')
console.log(member.getName())

2. モジュール内の個々の要素に別々に名前をつける

「クラス名 as 新しい名前」 のようにしてimportする。

sample.js
import { Member as MyMember, Class as MyClass} from './sample1'

let member = new MyMember('佐藤')
console.log(member.getName())

3. デフォルトのエクスポートをインポートする

モジュールに含まれる要素が一つだけであれば、デフォルトのエクスポートを宣言することができる。デフォルトエクスポートでは、クラス/関数などの名前は不要です。

sample1.js
export default class {
 static getPluss(a, b){
  return a + b
 }
}
sample2.js
import Math from './sample1'

console.log(Math.getPluss(1, 2))

参考資料

山田祥寛様 「javascript本格入門」

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?