一,module.exports和exports
Node里面的模块系统遵循的是CommonJS规范。
那问题又来了,什么是CommonJS规范呢?
由于js以前比较混乱,各写各的代码,没有一个模块的概念,而这个规范出来其实就是对模块的一个定义。
CommonJS定义的模块分为: 模块标识(module)、模块定义(exports) 、模块引用(require)
先解释 exports 和 module.exports
在一个node执行一个文件时,会给这个文件内生成一个 exports和module对象,
而module又有一个exports属性。他们之间的关系如下图,都指向同一块{}内存区域。
exports = module.exports = {
};
平时使用建议使用module.exports 导出,然后用require导入。
二,基本使用案例
1,exports和require
当使用exports时
let myFunc1 = function() {
... };
let myFunc2 = function() {
... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;
const m = require('./mymodule');
m.myFunc1();
即引入的这个m对象,内部包含了该文件所有exports出来的东西。
2,module.exports和require
const a=function a(ctx) {
ctx.body={
"message":"hello from a"
}
}
module.exports=a
const Router=require('koa-router')
const a= require('../api/ayewu')
const router =new Router()
router.get('/a',a)
module.exports=router
这时候a就是上面那个定义的函数了
三,再次理解
不难看出module是node.js自己主动为每个.js文件声明的一个变量,同时这个变量拥有两个参数,一个是索引id,一个是命名为exports的对象变量,exports用于存放用户导出的变量或属性。我们在对外导出时要做的就是:以key-value键值对的形式往module变量下的exports对象里面添加需要导出的变量或属性,如果像下面这样一个一个的导出:
function hello() {
console.log('Hello, world!');
}
function greet(name) {
console.log('Hello, ' + name + '!');
}
module.exports.hello = hello;
module.exports.greet = greet;
在require导入命名为test后。test.hello就是hello这个函数,test.greet就是greet这个函数。
于是在main.js中就可以引入使用:
module是node.js自己主动为每个.js文件声明的一个变量,其中有个参数exports,这个对象里面存着该文件导出的所有内容。
于是,可以这样写,更为方便快捷
function hello() {
console.log('Hello, world!');
}
function greet(name) {
console.log('Hello, ' + name + '!');
}
let varible="这是一个变量"
module.exports={
hello,
greet,
varible
}
//是这个的简写
// module.exports={
// hello:hello,
// greet:greet,
// varible:varible
// }