`if __name__ == '__main__'` equivalent in javascript es6 modules

后端 未结 3 2024
猫巷女王i
猫巷女王i 2020-12-04 01:53

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.

<
相关标签:
3条回答
  • 2020-12-04 02:25

    module.parent will help you:

    if(module.parent) {
        console.log('required module')
    } else {
        console.log('main')
    }
    
    0 讨论(0)
  • 2020-12-04 02:27

    The solution I see there is just to define the variable in the script you're importing. I.e. you define mainTest in main.js, and then use your existing if block.

    0 讨论(0)
  • 2020-12-04 02:31

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

    Example:

    // main.mjs
    import { fileURLToPath } from "url";
    import "./lib.mjs"
    
    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!
    
    0 讨论(0)
提交回复
热议问题