Why

  • Daily Code
  • Tree Shaking
    • ES6 module dependencies are determined, andThe state of the runtime is irrelevantCan be carried out reliablyStatic analysisThis is the foundation of tree-shaking

The characteristics of

ES6 modules are statically analyzed at compile time, so they cannot be manipulated

Because import is executed statically, import has a promotion effect

JavaScript You Didn't Know, Part 1

if (cond) {
  import xxx from "xxxx";
}
Copy the code

Want to SAO operation

dynamicimport()

Require. Ensure is only useful if the browser loads modules asynchronously.

The CommonJS module can verify that the module is loaded at run time.

  • Based on thePromise
  • It can be used anywhere in the script
export const foo = "HSQ MODULE";
Copy the code
<! DOCTYPEhtml>
<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" />
    <title>ESM</title>
  </head>

  <body></body>
</html>
<script type="module">
  const str = "./b.js";
  if (Math.random() < 0.5) {
    import("./b.js").then(({ foo }) = > {
      console.log(foo);
    });
  }
  import(str).then(({ foo }) = > {
    console.log(foo);
  });
</script>
Copy the code

Promise.allPerform parallel asynchronous loading

Promise.all([import("./a.js"), import("./b.js"), import("./c.js")]).then(
  ([a, { default: b }, { c }]) = > {
    console.log("a.js finish");
    console.log("b.js finish");
    console.log("c.js finish"); });Copy the code

Promise.racespeed

<! DOCTYPEhtml>
<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" />
    <title>Document</title>
  </head>

  <body></body>
</html>
<script>
  const CDNs = [
    {
      name: "Redux ".url: "https://cdn.bootcdn.net/ajax/libs/redux/4.1.0/redux.js"}, {name: "Lodash ".url: "https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.core.js",},];Promise.race([
    import(CDNs[0].url).then((res) = > CDNs[0].name),
    import(CDNs[1].url).then((res) = > CDNs[1].name),
  ]).then((res) = > {
    console.log(res);
  });
</script>
Copy the code