ES6定义的模块规范,在浏览器中怎么用?

导出模块

定义要导出的数据

//tools.js
const name = 'xiaoming';
const add = (num1, num2)=>{
    return num1 + num2;
}


class Person {
    constructor(name, age, ethicity){
        this.name = name;
        this.age = age;
        this.ethicity = ethicity;
    }

    introduce(){
        return `Hey, what's up, my name is ${this.name}, ${this.age} years old and I'm ${this.ethicity}`
    }
}

导出方法1

//tools.js
export {name, add, Person as Ren}; //可以用as重命名

导入方法,只能在模块<script type="module">中引用。

import {name, add, Ren} from './tool.js';
console.log(name);
console.log(add(1,100));
const xiaoming = new Ren('xiaoming',22,'Asian'icon_wink.png;
console.log(xiaoming.introduce());

导出方法2

//tools.js
export default {name, add, Person};

导入方法,只能在模块<script type="module">中引用。

import 随便取个名字 from './tools.js';
console.log(随便取个名字.name);
console.log(随便取个名字.add(1,100));
const xiaoming = new 随便取个名字.Person('xiaoming',22,'Asian'icon_wink.png;
console.log(xiaoming.introduce());

导入方法,可以在任意JS代码中运行。

// 可以用await
async function main(){
    const tools=await import('./tools.js'icon_wink.png;
    console.log(tools.name);
    console.log(tools.add(1,100));
    const xiaoming = new tools.Person('xiaoming',22,'Asian'icon_wink.png;
    console.log(xiaoming.introduce());
}

main();

// 也可以用then
import('./tools.js'icon_wink.png.then(tools=>{
    console.log(tools.name);
    console.log(tools.add(1,100));
    const xiaoming = new tools.Person('xiaoming',22,'Asian'icon_wink.png;
    console.log(xiaoming.introduce());
});

importimport() 区别

关于 import

  • 静态加载,在编译阶段运行
  • 总会提升到代码最开头
  • 只能在最外层使用,不能在if等作用域或函数里面使用
  • 如果要在if等作用域或函数里面运行,则使用import()

关于 import()

  • 动态加载,可以按需、按条件加载
  • 返回一个Promise
  • 不会提升到代码最开头
  • 可以在if作用域或者函数里面使用

exportexport default 区别

export default variable本质上是创建一个名为default的变量,作为本模块导出的唯一接口。其他信息赋值给 default后,将其导出。

export default 22; // 将 22 赋值给 default

const add = ()=>{};
export default add; // 将 add 复制给 default, 等同于下面一句
export {add as default};

import 随便什么名字 from './tools.js' // 等同于下面语句
import {default as 随便什么名字 } from './tools.js'

参考链接

ES6 入门教程, Module 的语法

文章目录