はじめに
アプリケーションが大きくなると機能を切り分けてモジュール化して管理していく必要が出てくる。
モジュール
とは機能ごとにクラスや関数を1つのファイルにまとめたものである。
機能ごとにモジュールを分けていくと、モジュールで外部の別のモジュールの機能を使用したい場面も出てくる。そういった時にimport
とexport
を利用することで、モジュール間で機能をやりとりすることができる。
import
を利用することで、外部から他のモジュールを読み込むことができ、読み込ませたい要素にexport
を記述してあげることでimport
が可能になる。
1つの要素をexport / importする
↓下記のモジュールのクラスを他のモジュールでも使えるようにしていく
// ファイルパスは ./lib/util.js とする
class Member {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
return this.firstName + this.lastName
}
}
export(デフォルトexport)
クラスを外部でも読み込めるようにするためにexport default
を記述する。
// クラスMemberをexport
export default class Member {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
return this.firstName + this.lastName
}
}
import
importで外部のモジュールにクラスを読み込む。
// import クラス名 from 'ファイルのパス名'
import Member from '@/lib/util';
// export defaultした場合、importでクラス名とは別の変数名をつけることも可能
import MyMember from '@/lib/util';
これで、クラスMemberが外部のモジュール(index.jsファイル)でも使用できるようになる。
複数の要素をexport / importする
↓下記のモジュールの2つのクラスを他のモジュールでも使えるようにしていく
// ファイルパスは ./lib/util.js とする
// ↓ クラスMember
class Member {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
return this.firstName + this.lastName
}
}
// ↓ クラスProduct
class Product {
constructor(name) {
this.name = name;
}
}
export(名前付きexport)
それぞれのクラスでexportを記述する方法
export class クラス名
と記述することでそれぞれのクラスをクラス名付きでexportできる。
// クラスMemberをexport
export class Member {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
return this.firstName + this.lastName
}
}
// クラスProductをexport
export class Product {
constructor(name) {
this.name = name;
}
}
最後にまとめてexportを記述する方法
宣言したクラスを最後にまとめてexportすることも可能。
class Member {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getName() {
return this.firstName + this.lastName
}
}
class Product {
constructor(name) {
this.name = name;
}
}
// クラスMemberとクラスProductをexport
export { Member, Product };
import
複数の要素をimportする場合は{ }
で囲む。
// クラスMemberとクラスProductをimport
import { Member, Product } from '@/lib/util';
これで、クラスMemberとクラスProductが外部のモジュール(index.jsファイル)でも使用できるようになる。