在node环境中,可以直接使用 node hello.js 运行一个js文件,在程序开发中,代码会越来越长,越写越多,维护时则难度越来越大;
为了编写的可维护性,我们可以根据功能将很多函数进行分组,拆分为多个js文件,这样的多个js文件称为模块;
'use strict';
var s = 'Hello';
function greet(name) {
console.log(s + ', ' + name + '!');
}
module.exports = greet;
以上hello.js文件,将greet这个函数对外导出,使其他引用hello.js文件的其他模块,可以使用greet函数;
例如
'use strict';
// 引入hello模块:
var greet = require('./hello');
var s = 'Michael';
greet(s); // Hello, Michael!
//注意到引入hello模块用Node提供的require函数
var greet = require('./hello');
在repuire引用时,应注意路径;
如果只写了模块名,node会依次在内置模块、全局模块和当前模块查找;
在引用时如果报错:
- 模块名是否正确
- 模块文件是否正确
- 相对路径是否正确
- commonJS规范
commonJS(模块加载机制),在这个规范下每个.js文件都是一个模块,他们内部各自使用的变量名和函数名各不冲突,互不影响。
module.exports = abc;//对外暴露变量
//在其他模块中引用变量
var def = require('模块名');
输出的变量可为:任意对象、函数、数组等,引入之后具体为什么,取决于被引入的模块输出了什么。
网友评论