2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

`preinstall: typesync`がgit clone直後にエラーになるのを防ぐ

Posted at

はじめに

npm scriptsにpreinstallを書いておくと、npm installとかyarn addの前に自動でスクリプトを実行してくれます。

TypeScriptで開発する場合、typesyncをpreinstall内で流すと、インストール時に@types/のパッケージがあれば自動インストールしてくれて便利です。

{
  "scripts": {
    "preinstall": "typesync"
  }
}

問題点

preinstallが走る時点でtypesyncがインストールされていないと、スクリプトの実行がエラーになり、続くインストールが止まってしまいます。
そのため、typesyncがdevDependenciesに含まれてるプロジェクトをgit cloneしてきた場合、clone直後のnpm installは失敗しちゃうんですね。

単独でtypesyncだけ先に入れるとか、そもそもグローバルインストールしておけば解決しますが、ローカルインストールでもgit clone && npm installが普通に成功する方法があります。

解決策

{
  "scripts": {
    "preinstall": "typesync || true"
  }
}

または

{
  "scripts": {
    "preinstall": "typesync || :"
  }
}

true は何もせず、終了ステータスとして'成功'を意味する 0 を返す。 本コマンドはシェルスクリプト中で正常終了するコマンドが必要な場合に 使われる。なお,シェルのビルトインコマンド ':' (コロン)は 同じ動作をより速く実行する。

スクリプト全体の終了ステータスが0であればインストールが実行されるので、シェル芸でcommand || trueすればcommandが失敗してもインストールは続くわけです。try-catchでエラーを握りつぶす感覚に近いですね。

typesyncに関しては、clone直後のインストールであれば、その時点で@types/が新規追加されることはなくて、package.json内の全パッケージが入ればOKですからね。

もちろん、typesync以外ではちゃんと異常終了を検知すべき場合も多いので、やみくもにエラーを握りつぶさないようには気をつけましょう。

では今日はこのへんで!

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?