created: 2023-11-13T02:21:53.492Z
nodejs で ts ファイルを実行するときの `-r ts-node/register` ってなにしてるの
-r
は node のコマンドラインオプションで、処理を実行する前に require
した状態にするもの。
-r, --require=... module to preload (option can be repeated)
でも、1 つモジュールを読み込んだだけで、なぜ JavaScript とは別な言語である TypeScript が実行できるのだろうか。
require.extensions
実は nodejs (commonjs) には require.extensions
という API が用意されていて、特定の拡張子のファイルを読み込んだ場合にフックの処理をかませることができるようになっている。
例
require.extenstions[".js"] = function (module, filename) {
var content = fs.readFileSync(filename, "utf8");
module._compile(internalModule.stripBOM(content), filename);
};
ドキュメント
Instruct require on how to handle certain file extensions.
ただし、現在はこの API は deprecated。
there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.
ts-node
ts-node ではこの API をつかっている。export されている register のコードですぐに登場する。