LoginSignup
8
7

More than 5 years have passed since last update.

TypeScript で複数のファイルに分割して npm ライブラリを作る

Last updated at Posted at 2018-02-16

npm ライブラリ、小さいうちは 1 つのファイルでいいんだけど大きくなってくるとファイル分割しないといけなくなる。
ググってたら1つのファイルに concat しないといけないとか、AMD にしろとか出たりして頭抱えてたけど、難しいことはなく普通に簡単にやることができた。

結論から言うと index.ts で export * from './xxx' するだけです。

ファイルを分割していってみよう

例えばこんな index.ts があったとします。これを分割していきます。

export const name = 'name'

export interface IHoge {
  hello(): void
}

export class Hoge implements IHoge {
  hello() {
    return 'Hello, ' + name
  }
}

ihoge.ts

export interface IHoge {
  hello(): void
}

hoge.ts

import { IHoge } from './ihoge'
import { name } from './index'

export class Hoge implements IHoge {
  hello() {
    return 'Hello, ' + name
  }
}

index.ts

export const name = 'name'
export * from './hoge'
export * from './ihoge'

export * from './xxx' でそのまま export できる。

部分的に export したければ export { Hoge } from './hoge' みたいにできそう。

package.json

package.json とかは今までと変わらず main と types を定義しておけば良い。

  "main": "out/index.js",
  "types": "out/index.d.ts",

おわり

これでファイル分割してライブラリファイルを定義できた。

雰囲気で TypeScript やっているので間違っていること・より良い方法があればぜひマサカリください :pray: :bow: :pray:

8
7
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
8
7