前端模块化
问题: 为什么前端要使用模块化?
模块化: 是具有特定功能的一个对象( 广义理解 )
模块定义的流程:
1.定义模块(对象)
2.导出模块
3.引用模块
好处:
1.可以存储多个独立的功能块
2.复用性高
种类
1. AMD( require.js)
2. CMD ( sea.js )
3. Common.js
AMD定义一个模块
define
// AMD
/*
目录
admDir
a.js
index.js
*/
// AMD定义 a.js
define ({
a: 1,
b: 2,
add: function(){}
})
// AMD引用 index.js
require([./a.js],function( moduleA ){
//moduleA指的就是定义来的对象
})
CMD定义模块
define
//CMD
/*
目录结构
b.js
index.js
*/
// 模块定义 b.js
define(function(require, exports, module) {
// 模块代码
});
//模块引用 index.js
require('./b.js',function( moduleB ){
//moduleB就是b模块中导出的内容
})
Common.js
Node.js使用了Common.js的规范
易错的理解:
common.js是属于node的 ×
node属于common.js ×
//common.js
/*
目录结构:
name.js
index.js
*/
//模块的定义 name.js
const nameObj = {
name: ‘Gabriel Yan ’
}
//模块的导出 name.js
module.exports = nameObj
//模块的引用
const nameObj = require(’./name.js’)
Node.js中Common.js规范的使用有三种类型:
-
内置模块( 内置模块指的是挂载在Node.js全局对象身上的api )
-
自定义模块
1. 模块的定义 ``` //举例 const student = { id: 1, name: 'Gabriel Yan' } const fn = function(){} ```
-
模块的导出
// 第一种导出 module.exports = student // 安全性不高 默认导出一个 //第二种导出 module.exports = { //批量导出,按需引用 student,fn }
-
模块的引用
// 这种引用对应第一种导出 const student = require('./xxx.js') // 这种引用对应第二种导出 const { student , fn } = require( './xxx.js ' )
注意:
在自定义模块引用时,require一定要写好路径
-
-
第三方模块
``` 1. 别人已经封装好的模块 2. 这个模块具备一些特定的功能 3. 这些模块存放在 www.npmjs.com 这个网站中 这些模块的文档也记录在内 格式: var/let/const 变量名 = require( 模块名称 ) 总结: 第一步,使用npm/cnpm 安装 第二部,在文件中引入 第三部,在www.npmjs.com这个网站中找到这个模块的文档,根据文档来使用 ```