Does ES6 module importing execute the code inside the imported file?

后端 未结 3 1761
别跟我提以往
别跟我提以往 2020-12-07 18:28

Does the code inside the js file gets run during the import? if yes, then once or each time? e.g.

// a.js
console.log(\"A\");
const a = \"a\"; 
export defaul         


        
相关标签:
3条回答
  • 2020-12-07 18:56

    Yes, it does, exactly one time.

    See http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-module-records:

    Do nothing if this module has already been evaluated. Otherwise, transitively evaluate all module dependences of this module and then evaluate this module

    0 讨论(0)
  • 2020-12-07 19:00

    In case someone is using TypeScript with "module": "es6" and wondering how to do this, use the globalThis keyword:

    function outputMsg(msg: string) : void {
        console.log(msg);
    }
    
    // export function for global scope
    globalThis.outputMsg = outputMsg;
    

    and then call outputMsg("my console output") as usual in the Chrome DevTools console and it should autocomplete and run your function.

    You could also rename your "global export":

    globalThis.myCrazyFunc = outputMsg;
    

    and call myCrazyFunc("crazy message") in the console.

    0 讨论(0)
  • 2020-12-07 19:06

    Actually that depends on where those modules are. If those are all in the same project then the code in a.js will indeed run once. But if a.js, b.js and c.js are in 3 separate packages then the code in a.js could run more than once.

    E.g. if you list package_b and package_c as dependencies in your project and both of those list package_a as a dependency, then the code will run twice.

    That's because npm installs two separate copies of package_a - one for package_b and one for package_c:

    node_modules/
    ├── package_b/
    │   └── node_modules/
    │       └── package_a/
    |           └── a.js
    └── package_c/
        └── node_modules/
            └── package_a/
                └── a.js
    

    So yes, the code in the module technically runs once, but you have two separate copies of the module, which each get imported once.

    I think this is a worthy answer as people landing on this question are unlikely to be aware of this, yet probably very much need to be if they landed on this question (especially given how badly wrong things will go thinking it works just like Ruby or Python).

    Here is an old but good article on understanding-the-npm-dependency-model with further detail on how and why npm does this.

    0 讨论(0)
提交回复
热议问题