npmでCLIを配布するならシェバンを忘れずに
先日、「MarkdownをSlackでコピペするためにいい感じに変換するCLI mdjanai」をnpmで公開しました(紹介記事)。
筆者が最初に公開したときにshebangを付け忘れてエラーになっていたので今回はその備忘録です。
エラーは静かに終わる
実際にコマンドを実行したら何も表示されずに異常終了しました。
原因
筆者は動作確認のときに次のようにnodeで実行していました。
node dist/index.jsこれなら当然nodeで実行されます。ただ、実際にCLIが実行される時はindex.jsが直接実行されるのでshebangが必要です。
対応
というわけでファイル冒頭にshebangを付けました。
#!/usr/bin/env nodeimport { foo } from "./foo"// ...どういうエラーが出たのか
修正前に 手元でビルドしたやつを、nodeではなくファイルを直接実行してみます。
./dist/index.jsdist/index.js: line 1: import: command not founddist/index.js: line 2: import: command not founddist/index.js: line 3: import: command not founddist/index.js: line 4: import: command not founddist/index.js: line 5: import: command not founddist/index.js: line 6: import: command not founddist/index.js: line 7: import: command not founddist/index.js: line 8: import: command not founddist/index.js: line 9: import: command not founddist/index.js: line 10: import: command not founddist/index.js: line 12: //#region: No such file or directorydist/index.js: line 13: var: command not founddist/index.js: line 15: //#endregion: No such file or directorydist/index.js: line 16: //#region: No such file or directorydist/index.js: line 17: syntax error near unexpected token `('dist/index.js: line 17: `const execFilePromise$1 = promisify(execFile);'command not foundやNo such file or directoryがずらずら出ます。というわけでshebang忘れないようにしましょう。
以上、Node.jsで書いたCLIをnpmで配布するならshebang忘れないで、という備忘録でした。