0
0

More than 1 year has passed since last update.

JavaScript(Node) でモジュールが直接実行されているかを判別する

Posted at

概要

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 でも動作確認済み

参考

0
0
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
0
0