xinggevip

Es2015 动态加载js模块
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
15
2019/06

Es2015 动态加载js模块

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>es6test</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but es6test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <script type="module">
      
      function config(num){
        switch(num){
          case 1:
            return './module/js1.js';
            break;
          case 2:
            return './module/js2.js';
            break;
        }
      }
      // 动态加载js模块
      import(config(2)).then(res=>{
        let {a,b} = res;
        console.log(a,b); // 10 20
      })


      // promise加载模块
      Promise.all([
        import('./module/js1.js'),
        import('./module/js2.js'),
      ]).then(([mod1,mod2])=>{
        console.log("Promise加载js模块");
        console.log(mod1);
        console.log(mod2);
      })
      

      // 异步加载模块
      async function main(){
        const m1 = await import('./module/js1.js');
        const m2 = await import('./module/js2.js');
        console.log(m1);
        console.log(m2);
      }
      main();


    </script>
    <!-- built files will be auto injected -->
  </body>
</html>

js1.js

let a = 10;
let b = 20;
export {
    a,
    b
}

js2.js

let a = 100;
let b = 200;
export {
    a,
    b
}
Last modification:June 15th, 2019 at 10:45 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment