javascript - `if __name__ == ' __main__ '` 相当于 javascript es6 模块

标签 javascript module ecmascript-6

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

例如,包含一个主脚本。

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

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

导入依赖项。

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

包括<script src=main.js></script>应该会产生来自 main.js 的控制台消息但不是 other.js。

我找到了answer to this question with regards to node ,但我对 es6 导入特别感兴趣

最佳答案

ES6 模块的替代方案是 now supported在节点中。使用新的import.meta内置的。 (不要忘记在 "type": "module" 中设置 package.json 。)

示例

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

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log("I print to stdout!");
}
// lib.js
import { fileURLToPath } from "url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log("I don't run, because I'm an imported module.");
}

$ node main.js输出:

I print to stdout!

实用功能

我喜欢import { isMain } from "./lib/utils.js"并通过import.meta.urlisMain() .

import { argv } from "process"
import { fileURLToPath } from "url"
/**
 * Check if a module is the main module launched with the node process.
 * Meaning the module is NOT imported by another module,
 * but was directly invoked by `node`, like this: `$ node main.js`
 *
 * @example
 * ```js
 * // main.js
 * import lib from "./lib.js"
 * import { isMain } from "./utils.js"
 *
 * if (isMain(import.meta.url)) {
 *   console.log("I print to stdout")
 * }
 *
 * // lib.js
 * import { isMain } from "./utils"
 *
 * if (isMain(import.meta.url)) {
 *   console.log("I don't run, because I'm an imported module")
 * }
 * ```
 *
 * @param {string} moduleUrl needs to be `import.meta.url`
 * @returns {boolean} true if the module is the main module
 */
export function isMain(moduleUrl) {
  const modulePath = fileURLToPath(moduleUrl)
  const [_binPath, mainScriptPath] = argv
  return modulePath === mainScriptPath
}

关于javascript - `if __name__ == ' __main__ '` 相当于 javascript es6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151554/

相关文章:

javascript - 如何使用 JS 打印 HTML 部分?

node.js - 你如何制作 Hapi.JS 插件/模块?

javascript - 在异步/等待函数完成之前执行的代码?

javascript - 如何从 Ecmascript 6 (ES6) 上的类对象中的事件回调函数访问对象成员

javascript - IE9 不反射(reflect) javascript 对页面的更改

javascript - ES6 yield (yield 1)(yield 2)(yield 3)()

function - 传递多个参数

javascript - 将 Array 转换为 Object 时奇怪的数据在 javascript 中丢失

javascript - ajax 附加 block 中的 if 语句

python - 从终端运行 python 程序时添加模块