上一篇文章,实现了模块化。但是最后还是存在如下的缺点
module.exports = value
exports.xxx = value
那么暴露的模块到底是什么? 肯定是个对象,是exports对象。
module.exports = value
,module.exports
本就有值,是空对象 {}
。然后把value值赋值给了module.exports
exports.xxx = value
就相当于向对象添加属性。引入模块
require(xxx)
服务器端
node.js
浏览器端
Browserify,打包工具。
新建一个COMMONJS文件夹,然后 npm init
初始化packe.json(只需要回车就可以)。 modules用于存放所有子模块。modules的同级创建一个app.js它去使用其他子模块。
package.json
中存放着一些包管理信息,和配置信息
{
"name": "commonjs",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
module.exports = value 暴露一个对象。
这就相当于定义一个对象变量。 let obj = {msg:''}
module.exports ={
msg:'module1',
foo(){
console.log(this.msg)
}
}
暴露一个函数 module.exports = function(){}
,当我们在他下面新加 module.export =function(){}
会将之前的覆盖掉。
这就相当于 定义一个 let a = function(){console.log(1)}
之后 再 a = function(){console.log(2)}
module.exports = function(){
console.log('module2')
}
// 在写会覆盖之前的
// module.exports = function(){
// console.log('覆盖了')
// }
exports.xxx = value 就可以随意向exports对象中添加内容,都可以导出。
// exports.xxx = value
exports.foo = function(){
console.log('foo() module3')
}
exports.bar = function(){
console.log('bar() module3')
}
调用,其他模块内容
使用require引入,因为是自定义模块所以是路径。
let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')
// 现在module1是一个对象
module1.foo()
// module2等价于函数
module2()
module3.bar()
module3.foo()
然后运行看一下效果, 在app.js的层级运行node app.js
uniq 为什么需要加 --save ?
因为npm5.0之后都是默认加上了--save。所以不加上--save也会下载
npm install uniq --save
在module3中添加一个数组
// exports.xxx = value
exports.foo = function(){
console.log('foo() module3')
}
exports.bar = function(){
console.log('bar() module3')
}
exports.arr = [6,8,4,2,3,3,11]
在app中引入数组和uniq。注意第三方模块和自定义模块引入方式的区别。
let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')
let uniq = require('uniq')
// 现在module1是一个对象
module1.foo()
// module2等价于函数
module2()
module3.bar()
module3.foo()
let data = uniq(module3.arr)
console.log(data) // [ 11, 2, 3, 4, 6, 8 ]
uniq可以去重,除了去重还可以排序。但是也存在一些问题,比如11排序到了2前面,因为它是按数字第一位编码排序的。