简体   繁体   中英

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

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

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

// b.js
import a from "./a"; // => console logs?

// c.js
import a from "./a"; // => console logs again?

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

The accepted answer is not fully correct. An installed module will execute once when imported, yes, but if the module is installed multiple times (which is very easy to do in node) then it will execute as many times as it is installed.

Consider what happens if a.js , b.js and c.js are in three separate packages ( package_a , package_b and package_c respectively) and package_b and package_c both specify package_a as a dependency, and your project specifies package_b and package_c :

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

Because package_a will be installed twice (as far as your project is concerned these are two totally different packages) the code in a.js will be imported, and therefore executed twice .

Many people landing on this question are unlikely to be aware of this quirk of node, yet probably need to be if they landed on this question.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM