TypeScript:export/importでモジュールを作成し外部でインポートする方法
開発規模が大きくなると1つのファイルで冗長なコードを書くよりも、複数のファイルに機能ごとにわけて開発したくなります。TypeScriptではモジュールを作成しそれを外部でインポートする仕組みとしてexport/import機能があります。
まず、外部モジュール側の簡単なプログラム例です。2つのクラスをモジュール化しています。classの前にexportというキーワードがありますが、これが「このクラスは外部で利用できる」という明示です。クラスだけでなく関数や変数にも使えます。今回はクラスの例となります。
export class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
export class Frend extends Person {
relation: string;
constructor(name: string, age: number, relation: string) {
super(name, age);
this.relation = relation;
}
getProfile(): string{
return `${this.name}は${this.age}歳で私の${this.relation}す。`
}
}
次にモジュールを使う側のプログラムです。
import {Person, Frend} from './module';
const person = new Person('taro', 28);
console.log(person.name);
console.log(person.age);
const friend = new Frend('ichiro', 28, 'classmate');
console.log(friend.getProfile());
//taro
//28
//ichiroは28歳で私のclassmateす。
以下のような書き方もできます。出力は上記のものと全く同じになります。
import * as module1 from './module';
const person = new module1.Person('taro', 28);
console.log(person.name);
console.log(person.age);
const friend = new module1.Frend('ichiro', 28, 'classmate');
console.log(friend.getProfile());
スポンサーリンク