CommonJs规范下的模块加载机制:每个js文件都是一个模块,它们内部各自使用的变量名和函数名都互不冲突

//在模块中对外输出变量
module.exports = variable;

//引入其他模块输出的对象
var foo = require('other_module');

通过示例代码演示模块的加载机制,两个文件分别是main.js和hello.js文件,每个文件都被认为是一个模块

//hello.js
'use strict';
var s = 'Hello';
function greet(name) {
    console.log(s + ', ' + name + '!');
}
module.exports = greet; //greet在外面可以被访问到

//main.js
'use strict';
var greet = require('./hello'); // 引入hello模块:
var s = 'Michael';
greet(s); // Hello, Michael!

模块引入的方式

//上面的代码中,引入hello模块
var greet = require('./hello'); 

//改变路径会方式
var greet = require('hello');  //Node会依次在内置模块、全局模块和当前模块下查找hello.js

results matching ""

    No results matching ""