仅在直接执行模块的情况下运行ES6代码 [英] Run ES6 code only if module is executed directly

查看:36
本文介绍了仅在直接执行模块的情况下运行ES6代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been working with ES6 modules, and I was looking for a way to include code that runs only if the file is executed directly (as opposed to being imported by another file). In languages like Python that have had earlier native module support, this is easy: simply wrap the code in a if __name__ == '__main__' block and the code will only run if the file is executed directly. This is quite useful for things like attaching basic testing code to a library. I am curious if there is any way to do this with ES6.

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

Ideally, I would like to have something like this:

文件 a.js

File a.js

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

文件 b.js

File b.js

import {pi} from 'a';
console.log(pi);

以便执行文件并获得以下输出:

So that one could execute the files and get the following outputs:

> somejsengine ./a.js
"This only prints if you run a.js directly."
> somejsengine ./b.js
3.1415

我也很好奇是否存在针对Node的CommonJS模块的解决方案(例如推荐答案

实际上,Node中可能存在这种情况:访问主模块

Actually there is a possibility for this in Node: Accessing the main module

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

You can check, if the module is run directly with require.main === module.

if (require.main === module) {
    console.log("This only prints if you run a.js directly.")
}

这篇关于仅在直接执行模块的情况下运行ES6代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆