仅当直接执行模块时才运行 ES6 代码[重复]

2024-02-08

我一直在使用 ES6 模块,并且我一直在寻找一种方法来包含运行的代码only如果直接执行该文件(而不是由另一个文件导入)。在像 Python 这样的早期支持本机模块的语言中,这很简单:只需将代码包装在if __name__ == '__main__'块,并且只有直接执行文件时代码才会运行。这对于将基本测试代码附加到库之类的事情非常有用。我很好奇是否有任何方法可以用 ES6 来做到这一点。

理想情况下,我想要这样的东西:

File a.js

export const pi = 3.1415
/* Some magical code here */
console.log("This only prints if you run a.js directly.")

File 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.js 仍然不支持 ES6 风格的模块 https://stackoverflow.com/questions/37132031/nodejs-plans-to-support-import-export-es6-es2015-modules).


事实上,Node 中存在这样的可能性:访问主模块 https://nodejs.org/api/modules.html#modules_accessing_the_main_module

您可以检查该模块是否直接运行require.main === module.

if (require.main === module) {
    console.log("This only prints if you run a.js directly.")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅当直接执行模块时才运行 ES6 代码[重复] 的相关文章

随机推荐