import * as m1 from"./module.js" console.log(m1.PI)//访问暴露的属性 //使用不被暴露的方法 console.log(m1.sum(10,20)) //Uncaught TypeError: m1.sum is not a function
分别导入
1 2 3 4
import {PI} from"./module.js" console.log(PI) //使用不被暴露的方法 console.log(sum(10,20)) //Uncaught TypeError: m1.sum is not a function
统一导出
在文件的最后使用export{}按需暴露
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//module.js constPI = 3.14 functionsum(a,b){ return a+b } classPerson{ constructor(name,age){ this.name = name this.age = age } sayHello(){ console.log(`hello,my name is ${this.name},${this.age} years old`) } } export{PI,sum,Person}
全部导入
1 2 3 4 5
import * as m1 from"./module.js" console.log(m1.PI) //3.14 console.log(m1.sum(10,20)) //30 let person = new m1.Person("xiaobai",18) person.sayHello() //hello,my name is xiaobai,18 years old