一:模块化雏形:
//小明编写的js.js:
;var modulea=(function(){
var flag=true;
return flag;
})()
//小明编写的js2.js
if(modulea.flag==true){
xxxx;
}
二、出现了模块化规范
因为模块化雏形比较复杂,所以出现了模块化规范
比如commonjs,amd,cmd,es6
三、commonjs:
//小明编写的js.js:
module.export{
flag,xxx
}
//小明编写的js2.js:
let{flag,xxx}=require('aaa.js');
四、es6:关键字export和import
index.html引入script时,注意加上type=‘module’
小明写的js.js代码如下
//1.一般使用
export{flag,sum},
//2.边定义边导出
export var flag = true;
//3.导出方法
export function mul(a,b){
console.log(a*b);
}
//4.导出类
export class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
run(){console.log(this.name+'在奔跑');}
}
//5.默认导出
const address='北京市';//默认
export default address;//默认
export default function(){//不用起名字了
xxx
}
小明编写的js2.js代码如下:
//1.一般导入,以及导入类的使用
import {flag,Person} from 'aaa.js';
const p=new Person()
p.run()
//2.默认导入用法
import addr from 'aaa.js'//默认
//3.全部导入进来
import * as aaa from'aaa.js'
console.log(aaa.name)