`if __name__ == '__main__'` 等效于 javascript es6 模块 [英] `if __name__ == '__main__'` equivalent in javascript es6 modules

查看:16
本文介绍了`if __name__ == '__main__'` 等效于 javascript es6 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查 JavaScript 文件是否正在直接运行,或者是否需要作为 es6 模块导入的一部分.

例如包含一个主脚本.

//main.js导入'./其他';如果(主测试){console.log('这应该运行');}

导入依赖项.

//other.js如果(主测试){console.log('这不应该运行');}

包括 <script src=main.js></script> 应该导致来自 main.js 而不是 other.js 的控制台消息.

我找到了关于节点的这个问题的答案,但我对 es6 导入特别感兴趣

解决方案

ES6 模块的替代方案是 现在在 Node.js 中支持.使用新的 import.meta 内置.

示例:

//main.mjs导入./lib.mjs"从url"导入 { fileURLToPath };if (process.argv[1] === fileURLToPath(import.meta.url)) {console.log(`main run!`);}

//lib.mjs从url"导入 { fileURLToPath };if (process.argv[1] === fileURLToPath(import.meta.url)) {console.log(`lib 运行了!`);}

和我们的输出:

main 跑了!

Is it possible to check if JavaScript file is being run directly or if it was required as part of an es6 module import.

for example a main script is included.

// main.js
import './other';

if (mainTest){
  console.log('This should run');
}

which imports a dependency.

// other.js
if (mainTest){
  console.log('This should never run');
}

including <script src=main.js></script> should result in the console message from main.js but not other.js.

I found the answer to this question with regards to node, but I am interested specifically for es6 imports

解决方案

An alternative for ES6 modules is now supported in Node. Using the new import.meta builtin.

Example:

// main.mjs
import "./lib.mjs"
import { fileURLToPath } from "url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log(`main ran!`);
}

// lib.mjs
import { fileURLToPath } from "url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log(`lib ran!`);
}

and our output:

main ran!

这篇关于`if __name__ == '__main__'` 等效于 javascript es6 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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