为何须要模块化开发?css
随着代码复杂程度的提升, 项目也变得愈来愈难维护, JavaScript模块化 也所以油然而生, 这应该是你们最熟悉的一种加载方式, 可是缺点也比较明显html
<script src="jquery.js"></script>
<script src="jquery_scroller.js"></script>
<script src="bootstarp.js"></script>
<script src="main.js"></script>
复制代码
CommonJsvue
一个文件就是一个模块, 其内部定义的变量, 方法都处于该模块内, 不会对外暴露.node
主要语法:jquery
使用 require 来加载模块 使用 exports 或者 module.exports 暴露模块中的内容webpack
demoios
新建 a.js, 导出 name 和 sayHelloweb
// a.js
const name = 'Bob'
function sayHello(name) {
console.log(`Hello ${name}`)
}
module.exports.name = name
module.exports.sayHello = sayHello
复制代码
在 b.js 中引入 a 并调用面试
// b.js
const a = require('./a')
const name = a.name
console.log(name) // Bob
a.sayHello(name) // Hello Bob
复制代码
因为 CommonJs 是同步加载的模块的, 在服务端(node), 文件都在硬盘上, 因此同步加载也无所谓, 可是在浏览器端, 同步加载就体验很差了. 因此 CommonJs 主要使用于 node 环境下.vuex
AMD
AMD 全称为 Asynchromous Module Definition(异步模块定义), 实现了异步加载模块. require.js 实现了 AMD 规范
主要语法:
require([module], callback) // 导入 define(id, [depends], callback) // 导出模块 新建 a.js, 输入如下内容
define(function() {
let alertName = function(str) {
alert('I am ' + str)
}
let alertAge = function(num) {
alert('I am ' + num + ' years old')
}
return {
alertName: alertName,
alertAge: alertAge
}
})
复制代码
在 test.html 中调用 a 模块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./require.js"></script>
<script>
require(['a'], function (alert) {
alert.alertName('JohnZhu')
alert.alertAge(21)
})
</script>
</body>
</html>
复制代码
CMD
CMD规范 是阿里的玉伯提出, sea.js 实现。 实现了按需加载
与 AMD 的区别:
对于依赖的模块 AMD 提早执行,而 CMD 是延迟执行 CMD 推崇依赖就近, AMD 推崇依赖前置
//AMD2.0以前
require(['./a', './b'], function(a, b) {
a.doSomething();
b.doSomething();
})
// AMD2.0以后
define(['./a', './b'], function(a, b) {
a.doSomething();
b.doSomething();
})
// CMD
define(function(require, exports, module) {
var a = require('./a');
a.doSomething();
var b = require('./b');
b.doSomething();
})
复制代码
ES6
ES6 模块化方案是最规范的方案, 将来也是主流, 对于咱们来讲也是常常使用与熟悉的. 不过如今的浏览器还不兼容, 使用须要 babel 转码
使用 export 导出模块 使用 import 导入模块
import Vue from 'vue'
import axios from 'axios'
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
created() {
console.log('Hello World')
}
}
复制代码
了解更多 本次给你们推荐一个免费的学习群,里面归纳移动应用网站开发,css,html,webpack,vue node angular以及面试资源等。 对web开发技术感兴趣的同窗,欢迎加入Q群:864305860,无论你是小白仍是大牛我都欢迎,还有大牛整理的一套高效率学习路线和教程与您免费分享,同时天天更新视频资料。 最后,祝你们早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。