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

后端 未结 3 1760
别跟我提以往
别跟我提以往 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 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.

提交回复
热议问题