是否可以检查 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.url
至isMain()
.
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/