[英]`if __name__ == '__main__'` equivalent in javascript es6 modules
是否可以檢查 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 的控制台消息。
我找到了關於 node 的這個問題的答案,但我對 es6 導入特別感興趣
Node.js 現在支持ES6 模塊的替代方案。 使用新的import.meta
內置。
例子:
// 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!`);
}
和我們的輸出:
main ran!
module.parent
會幫助你:
if(module.parent) {
console.log('required module')
} else {
console.log('main')
}
我看到的解決方案只是在您導入的腳本中定義變量。 即您在main.js
定義mainTest
,然后使用您現有的 if 塊。
module.parent
在 Node.js v14.6.0 中被棄用,但我們可以使用require.main
。
function main() {
console.log("You're running the main file!");
}
if (require.main === module) {
main();
}
可以在此處找到相關答案。
如果您在 Node.js 中使用類型模塊運行,並且不要將文件命名為相同,並且不想導入庫,並且想要 1 行代碼,這將起作用:
if(process.argv[1].split('/')[process.argv[1].split('/').length - 1] === import.meta.url.split('/')[import.meta.url.split('/').length - 1]) {
console.log("called from commandline")
} else {
console.log("imported")
}
以下簡單代碼可用。
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
if (__filename === process.argv[1]) {
console.log("main");
} else {
console.log("not main");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.