LoginSignup
5
3

More than 3 years have passed since last update.

ngコマンドの中身を覗いてみる

Posted at

Disclaimer: この記事を執筆現在私はGoogleで働いています。記事内でGoogleのプロダクトについて言及するため明確に所属を記載していますが、このことは私が記事内に登場するプロダクトについて特別詳しい知識を持っていることを意味しません。1ユーザーが書いた記事としてお読みいただければ幸いです。


唐突に自作コマンドを作りたくなって、参考にngコマンドを開いてみたところ中身が気になったので読んでみました:dog2: 読んでいるファイルの全量はこちらです。

第一部

ng
#!/usr/bin/env node
'use strict';

Shebangでインタプリタにnodeを指定して、strictモードを使う宣言をしています。

第二部

ng

// Provide a title to the process in `ps`.
// Due to an obscure Mac bug, do not start this title with any symbol.
try {
  process.title = 'ng ' + Array.from(process.argv).slice(2).join(' ');
} catch (_) {
  // If an error happened above, use the most basic title.
  process.title = 'ng';
}

psで使われるプロセスのタイトルを決めているようです。process.argvの2個目以降の要素(=コマンドライン引数)を取り出して結合したものをngと繋いでprocess.titleとします。ちなみに0個目にはnodeのフルパス、1個目にはコマンドのスクリプトファイルのフルパスが格納されています。エラーが発生した際には、一番普通のネーミングということでngになります。

第三部

ng
// This node version check ensures that extremely old versions of node are not used.
// These may not support ES2015 features such as const/let/async/await/etc.
// These would then crash with a hard to diagnose error message.
// tslint:disable-next-line: no-var-keyword
var version = process.versions.node.split('.').map(part => Number(part));
if (version[0] < 10 || version[0] === 11 || (version[0] === 10 && version[1] < 13)) {
  process.stderr.write(
    'Node.js version ' + process.verson + ' detected.\n' +
    'The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.\n\n' +
    'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
  );

  process.exit(3);
}

process.versions.nodeにはnodeのバージョンが11.13.0のようなフォーマットで入ってくるので.で区切って配列に詰め直します。そして、

  • メジャーバージョンが9以下 or
  • メジャーバージョンが11 or
  • メジャーバージョンが10でマイナーバージョンが12以下

の場合には「AngularCLIはv10.13またはv12以上のNodeを必要とします。(意訳)」のメッセージを表示して終了します。

第四部

ng

require('../lib/init');

手元でwhich ngすると/usr/local/bin/ngで、この相対パス通りに遡ってもinitというファイルがないので一瞬???となりましたが、「Node.js スクリプトをコマンドのように使えるようにする方法」という記事をみて謎がとけました。
ls -lすると

$ ls -l /usr/local/bin/ng
lrwxr-xr-x ...(割愛)... /usr/local/bin/ng -> ../lib/node_modules/@angular/cli/bin/ng

となっていて実際は../lib/node_modules/@angular/cli/bin/ngにいることがわかります。
そこでls /usr/local/lib/node_modules/@angular/cliしてみると、確かにlibフォルダーがいてその中にinit.jsがいます。ということで、最後にこれを読み込んでいました。


おしまいです。最初の最初しか読んでいないのでそんなにAngular独特の内容はないですね。
気が向いたら最後に読み込んでいたinit.tsの中身ものぞいてみようと思います:sunny:

5
3
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
5
3