es6模块化概念
在es6之前js对于模块化的支持不是很友好,主要通过 CommonJS(服务器端) 和 CMD/AMD(浏览器端)来实现,es6在语言标准的层面实现了模块功能,而且相当简单,可以完全取代以上两个,当前es6的module已经成为了浏览器和服务器通用的模块的解决方案,非常实用
es6模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系以及我们输入输出的变量到底是什么
es6的模块化命令
es6模块功能主要有两个命令构成:
export: 抛出,用于规定模块的对外接口import: 引入,用于输入其他模块提供的功能
一个模块就是一个独立的文件
export:需要抛出的对象,在前面加上export,或者使用 export default xxx;
export const name = 'Max';
export const age = '23';
export function sayName() {
return `请叫我${name}`;
}
export const obj = {
foo: 'foo'
}
class Person {
constructor() {
}
sayAge() {
console.log(age);
}
}
export default Person;//export default抛出,在一个组件中只能使用一次,收的时候放在{}外
import:在浏览器模块中,需要给当前的script标签加一个类型module
<script type="module">
import Person, { name, age, sayName, obj } from './index.js';//把export的对象放入{}内
// import * as index from './index.js';
console.log(name);//Max
console.log(age);//23
console.log(sayName());//请叫我Max
console.log(obj);//{foo: "foo"}
console.log(Person())
const p = new Person;//实例化Person,就可以通过实例化对象调用Person的方法
p.sayAge();//23
</script>
import * as xxx from './xxx.js'; 是一次性接收组件内抛出的所有对象,然后在引入的文件内需要调用的地方以 xxx. 为关键字引入对象,例如 index.name ,通过 export default 抛出的对象则需要用 index.default 接收
console.log(index)
//------------------------------------------------
Module {…}
age: "23"
default: class Person
name: "Max"
obj: Object
sayName: ƒ sayName()
Symbol(Symbol.toStringTag): "Module"
get age: ƒ ()
set age: ƒ ()
get default: ƒ ()
set default: ƒ ()
get name: ƒ ()
set name: ƒ ()
get obj: ƒ ()
set obj: ƒ ()
get sayName: ƒ ()
set sayName: ƒ ()