运行 ES6 代码仅当模块直接执行时
Run ES6 code only if module is executed directly
我一直在使用 ES6 模块,我一直在寻找一种方法来包含 运行s only 如果文件被直接执行的代码(而不是被另一个文件导入)。在像 Python 这样有较早的本地模块支持的语言中,这很容易:只需将代码包装在 if __name__ == '__main__'
块中,如果直接执行文件,代码只会 运行 。这对于将基本测试代码附加到库之类的事情非常有用。我很好奇是否有任何方法可以用 ES6 做到这一点。
理想情况下,我想要这样的东西:
文件a.js
export const pi = 3.1415
/* Some magical code here */
console.log("This only prints if you run a.js directly.")
文件b.js
import {pi} from 'a';
console.log(pi);
这样就可以执行文件并获得以下输出:
> somejsengine ./a.js
"This only prints if you run a.js directly."
> somejsengine ./b.js
3.1415
我也很好奇 Node 的 CommonJS 模块是否存在这样的解决方案(如 ) .
实际上在 Node 中有这样的可能性:
Accessing the main module
您可以直接用require.main === module
.
检查模块是否是运行
if (require.main === module) {
console.log("This only prints if you run a.js directly.")
}
我一直在使用 ES6 模块,我一直在寻找一种方法来包含 运行s only 如果文件被直接执行的代码(而不是被另一个文件导入)。在像 Python 这样有较早的本地模块支持的语言中,这很容易:只需将代码包装在 if __name__ == '__main__'
块中,如果直接执行文件,代码只会 运行 。这对于将基本测试代码附加到库之类的事情非常有用。我很好奇是否有任何方法可以用 ES6 做到这一点。
理想情况下,我想要这样的东西:
文件a.js
export const pi = 3.1415
/* Some magical code here */
console.log("This only prints if you run a.js directly.")
文件b.js
import {pi} from 'a';
console.log(pi);
这样就可以执行文件并获得以下输出:
> somejsengine ./a.js
"This only prints if you run a.js directly."
> somejsengine ./b.js
3.1415
我也很好奇 Node 的 CommonJS 模块是否存在这样的解决方案(如
实际上在 Node 中有这样的可能性: Accessing the main module
您可以直接用require.main === module
.
if (require.main === module) {
console.log("This only prints if you run a.js directly.")
}