我找到了关于节点的这个问题的答案,但我对 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.jsimport './other';if (mainTest){ console.log('This should run');}which imports a dependency.// other.jsif (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.mjsimport "./lib.mjs"import { fileURLToPath } from "url";if (process.argv[1] === fileURLToPath(import.meta.url)) { console.log(`main ran!`);}// lib.mjsimport { 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 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!