ES6 Module学习笔记

基本语法

  1. export

    1. 导出数据:

      1
      2
      3
      export var color = "red";
      export let name = "jacky";
      export const magicNumber = 7;
    2. 导出函数

      1
      2
      3
      export function sum(num1, num2) {
      return num1 + num2;
      }
    3. 导出类

      1
      2
      3
      4
      5
      6
      export class Rectangle {
      constructor(length, width) {
      this.length = length;
      this.width = width;
      }
      }
    4. 定义函数,然后导出引用

  2. import

    import { identifier1, identifier2 } from './example.js'

    导入绑定列表不是解构对象

    1. 导入单个
    2. 导入多个
    3. 导入整个模块 import * as example from './example.js'
    4. 同一个模块只执行一次,实例化模块将保存在内存中
  3. import export只能在其他语句之外

  4. import语句创建的是只读绑定,而非原始绑定。

  5. as关键词,更改导入导出的名字

  6. default 模块默认值

    1. export default function(...) {...}
    2. export default sum;
    3. export { sum as default, a, b, c}
  7. 重新导出 export { sum as add } from './example'

其他

  1. 无绑定导入

    1. 内建对象(array, object)的共享定义可以在模块中访问,其更改效果可反映在其他模块中。
    2. Array.prototype.pushAll = function(...) {...} 可以通过 import "./example.js" 生效
  2. 加载模块

    1. ES6只定义语法,没有定义如何加载。

    2. 加载机制抽象到一个未定义内部方法HostResolveImportedModule

    3. Web 浏览器

      1. <script> 增加一个type: type="module"

        1
        2
        3
        4
        5
        <script type="module" src="./example.js"></script>
        <script type="module">
        import { sum } from "./example.js";
        ...
        </script>

        当浏览器不能识别type="module"时会忽略script标签

      2. 加载时会自动应用defer并按照html顺序加载,且都是按需加载,递归加载并解析相关资源,然后递归执行。

      3. 异步加载

        1. async 保证所有模块都下载完成
        2. 不保证模块执行顺序
      4. 作为worker加载,添加第二参数{type: "module"}

    4. 模块说明符

      • / 根目录
      • ./ 当前目录
      • ../ 父目录
      • URL 格式