在Node 中的JavaScript有一个重要的概念:模块系统
- 模块作用域
- 使用require方法用来加载模块
- 使用exports接口对象用来导出模块中的成员
1.加载require
语法:
var 自定义变量名称 = require(‘模块’)
两个作用:
- 执行被加载模块中的代码
- 得到被加载模块中的
exports
导出接口对象
2.导出exports
- Node 中是模块作用域,默认文件中所有成员只在当前文件模块有效
- 对于希望可以被其它模块访问的成员,需要把这些公开的成员都挂载到
expors
接口对象中
导出多个成员(必须在对象中)
exports.a = 123
exports.b = 'hello'
exports.c = function () {
console.log('ccc)
}
exports.d = {
foo: 'bar'
}
导出单个成员(拿到的就是:函数、字符串)
module.exports = 'hello'
也可以这样导出多个成员:
module.exports = {
add:function () {
return x + y
},
str: 'hello'
}