概要
Python の if __name__ == 'main'
と同じことを JavaScript(Node) でも行いたい。
結論
if (require.main === module) {
}
動作確認
foo.js
function doSomething() {
console.log('doSomething!!')
}
module.exports = {
doSomething
}
// foo.js が直接実行された場合だけ、すぐに doSomething を実行する
if (require.main === module) {
doSomething()
}
bar.js
const { doSomething } = require('./foo')
$ node foo.js
doSomething!!
$ node bar.js
$
コードは割愛するが、TypeScript + ESM でも動作確認済み
参考