简体   繁体   中英

How to make the export functions global after an import() call in JavaScript

So we have this function in JavaScript:

// main.js
import('./module.js');

Then we have the module file:

// module.js
export function SomeFunctionA() {
}
  
export function SomeFunctionB() {
}

Is it possible to use the import() call and make all "export " functions from the module available globally? I saw some articles on Webpack. Please, no Webpack or any add-on libraries to make this work.

The import returns a promise, so you could do so using:

// main.js
var bob = import ('./module.js');
bob.then((mod) => {
    console.log(mod);
    for(var prop in mod){
        // maybe a little nicer to check hasOwnProperty?
        // but you get the idea for brevity
        window[prop] = mod[prop];
    }
});

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