はじめに
Typescriptの学習を引き続きしていく。今回はファイルを分割する際の使うexport
について触れたい
モジュールシステム
- ECMAScript2015から導入されたJavascirptの機能
- 原則、1ファイル1モジュール
- 外部に提供したい要素をexportして、外部から提供されたものをimportする
2種類のexport
2種類のexportが存在する。それぞれコードを記述して考えていく。
defaule export(名前なしexport)
- 宣言済みの変数や関数をdefault export
- 宣言と同時にdefault exportになる
注意:アロー関数は書けない
defaukt1.ts
// 宣言済みの変数や関数を default export
const function1 = (): void => {
console.log("This is default exported function 1")
}
export default function1
default2.ts
// 宣言と同時に default export
// アロー関数としては書けない→Javascriptの制約で書けない
export default function function2(): void {
console.log("This is default exported function 2")
}
named export(名前つきexport)
- 1ファイルから複数モジュールをexportできる
- エントリポイントと呼ばれるファイルに名前付きexportをまとめる
named.ts
/***** named export ( 名前付き export ) *****/
// 1ファイルから複数モジュールを export できる
export const function3 = (): void => {
console.log("This is named exported function 3")
}
export function function4(): void {
console.log("This is named exported function 4")
}
エントリポイントを用意する
- 慣習的に
index.ts
が用いられる
index.ts
// default export された module をさらに named export できる
// ここのfunction1は便宜上function1にしている→変更もできるよ!
export { default as function1 } from './default1'
export { default as function2 } from './default2'
// named export された module をさらに named export できる
// どのファイルから、どんな名前でexportするのか?
export { function3, function4 } from './named'
階層構造.md
module
|- index.ts
|- default1.ts
|- default2.ts
|- named.ts
おわりに
アロー関数が使えるのかや、書き方に癖があったりなど初学者に少し優しくないなと思った。慣れる日が来るのだろうか