LoginSignup
182
112

More than 1 year has passed since last update.

TypeScriptの@typesパッケージをtypesyncで自動管理する

Last updated at Posted at 2020-05-25

地味に面倒な型定義パッケージの追加。
自動で入れてくれないかな〜と思ったことはありませんか

今回はそんな悩みを解決してくれるパッケージをご紹介します。

typesync

GitHub - jeffijoe/typesync
preview

Install missing TypeScript typings for dependencies in your package.json.

package.jsonを見て足りない型定義パッケージがあれば自動で追加してくれるパッケージです。

インストール

さっそくインストールしましょう

$ yarn add -D typesync

# もしくは
$ npm install -D typesync

あとはpreinstallで実行するように設定するだけです

package.json
  "scripts": {
    ...
     // 初回インストール時にはtypesyncがないので || : を付け加えてエラーを無視します。
+    "preinstall": "typesync || :"
  }

もしうまく動かない場合はpostinstallに設定します。
なお、postinstallの場合はpackage.jsonが変更されるだけなので、再度インストールを叩く必要があります。

package.json
  "scripts": {
    ...
+    "postinstall": "typesync"

     // @types追加後に自動インストールする場合は
+    "postinstall": "typesync && yarn install --ignore-scripts"
     // もしくは
+    "postinstall": "typesync && npm install --ignore-scripts"
  }

使ってみる

試しに react-redux-realworld-example-app というプロジェクトでtypesyncを使ってみます

$ yarn
yarn install v1.22.4
$ typesync | :
⠴  Syncing type definitions in package.json...
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
✨  Done in 6.63s.

インストール後

package.json
  "devDependencies": {
    ...
+    "@types/history": "^4.7.6",
+    "@types/marked": "^0.7.4",
+    "@types/prop-types": "^15.7.3",
+    "@types/react": "^16.9.35",
+    "@types/react-dom": "^16.9.8",
+    "@types/react-redux": "^5.0.21",
+    "@types/react-router": "^4.4.5",
+    "@types/react-router-dom": "^4.3.5",
+    "@types/react-router-redux": "^5.0.18",
+    "@types/redux-logger": "^3.0.7",
+    "@types/superagent": "^3.8.7",
  }

いい感じに追加されました。

もう一つ、 vue-realworld-example-app でも試してみます。

package.json
  "devDependencies": {
    ...
+    "@types/babel-core": "6.25.6",
+    "@types/babel__core": "^7.1.7",
+    "@types/babel__preset-env": "^7.9.0",
+    "@types/marked": "^0.7.4",
+    "@types/node-sass": "^4.11.1",
  }

ちゃんと追加されてますね
vueの型定義は本家に含まれてるのでスキップされたようです。

詳細設定

基本的にはこのままでも動くのですが、 .typesyncrc というファイルを追加することで @types を更新されたくないパッケージを指定することもできます。

{
    "ignorePackages": ["react", "nodemon"]
}

詳しい使い方などは こちら を参考にしてください。

仕組み

結構シンプルな仕組みで動いています。

  1. すべての@￰typesパッケージの情報を取得
  2. package.jsonと照らし合わせる
  3. いい感じに@￰typesパッケージをpackage.jsonに反映

ここで素晴らしいのが、

  • できるだけ近いバージョンのものをsemver準拠で入れてくれる
  • 型定義がすでに含まれているパッケージはスキップ
  • 参照しなくなったパッケージの分は削除してくれる

ですね。

なお、@￰typesパッケージ情報はTypeScript Types Searchで読み込まれているJSONファイルを取得しているようです。

まとめ

考えることが1つ減るので地味に嬉しいですね。

皆さんも型定義管理のちょっぴり無駄な時間から解放されましょう!

182
112
2

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
182
112