如何编写一个 module ,既能被引用(require),又能作为执行入口?
发布于 8 年前 作者 g8up 4145 次浏览 来自 问答

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

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

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

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

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

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

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

回到顶部