如何编写一个 module ,既能被引用(require),又能作为执行入口?
 发布于 9 年前  作者 g8up  5361 次预览  最后一次回复是 9 年前  来自 问答 

编写一个 app.js 通过何种方式既能被require('./app.js'),又能node app.js来作为执行入口?

// app.js
module.exports = {
};
4 回复
klesh

写完 exports 之后,在最后面追加:

if (require.main === module) {
  // code to be executed while current file is the entry point
}
yunkou

@klesh 没太看懂 require.main === module 是什么意思能解释下么?

stonephp

伪命题,本身就可以的,require也会执行代码。

DevinXian

简单点,分开成两个文件,一个引用另一个不就完了