一、ES6 规范
es6 规范语法
export default name #导出模块
import [name] from 'moduleNamePath' #引用模块
暴露模块
1、分别暴露
export let school = '蜗牛学习'
export function name(params) {
console.log("aaaa");
}
2、统一暴露
let school = '蜗牛学习'
function name(params) {
console.log("aaaa");
}
export {
school,
name
}
3、默认暴露
let school = '蜗牛学习'
function names() {
console.log("aaaa");
}
export default{
school,
names
}
引入模块
1、通用方式
import * as m from "./index.js";
2、解构赋值形式
//对应分别暴露
import {school,names} from "./index.js";
//对应统一暴露
import {school as sch,names} from "./index.js";
//对应默认暴露
import {default as m} from "./index.js";
3、简便形式(只针对默认暴露)
import m from "./index.js";
多模块导出导入
//util.js
const indexDataHandler = () => {}
export default {
indexDataHandler
}
//index.js
export { default as util } from './util/util.js'
//main.js
import * as common from './common/index.js'
Vue.prototype.common = common
解构赋值方式
export const amtHandle = () => {
console.log(2222);
}
import { amtHandle } from './../../common/util';
浏览器引入模块
// 导出模块
export let school = '蜗牛学习'
export function name(params) {
console.log("aaaa");
}
//引入模块
<script type="module">
import * as m from "./index.js";
console.log(m);
m.name()
</script>
动态import()
import()返回的是一个Promise对象,可以在需要的时候,再加载某个模块。
hello.js
function hello() {
alert('hello')
}
index.js
btn.onclick = function () {
import('./hello.js').then(element=>{
element.hello()
})
}
二、commonjs 规范
NodeJS、Browserify
暴露模块
//header.js
function Header(){}
module.exports = Header;
导入模块
const Header = require('./header.js);
三、AMD 规范
requireJS
AMD异步模块定义
//是RequireJS在推广过程中对模块定义的规范化产出
define(id?,dependencies?,factory)
define(function(){
var exports = {};
exports.sayHello = function(){
console.log("hello word")
};
return exports;
})
四、CMD 规范
seaJS
CMD同步模块定义
//是SeaJS在推广过程中对模块定义的规范化产出(淘宝团队)
//兼容多种模块规范写法
;(function (name, definition) {
// 检测上下文环境是否为AMD或
var hasDefine = typeof define === 'function',
// 检查上下文环境是否为Node
hasExports = typeof module !== 'undefined' && module.exports;
if (hasDefine) {
// AMD环境或CMD环境
define(definition);
} else if (hasExports) {
// 定义为普通Node模块
module.exports = definition();
} else {
// 将模块的执行结果挂在window变量中,在浏览器中this指向window对象
this[name] = definition();
}
})('hello', function () {
var hello = function () {};
return hello;
});