require(“xx.js”)获取的就是export(也就是说(exports后面直接跟等号),export等号后面的东西可以怎么使用,require等号前面的就可以怎么使用,如例:1;也或者是说(export后面不是直接跟等号),exports可以怎么使用,require等号前面的就可以怎么使用,如例:2);如果js文件中有多个export,则通过require获取到的是一个对象类型,如例3:
- 例1、
//hello.js
module.exports = function() {
console.log("Hello World!");
}
//main.js
var hello = require("./hello");
hello();
//结果:Hello World!
- 例2、
//hello.js
module.exports.world = function() {
console.log("Hello World!");
}
//main.js
var hello = require("./hello");
hello.world();
//结果:Hello World!
*例3、
//hello.js
module.exports.word = function(){console.log("world!");}
module.exports.hello = function(){ console.log("hello!");}
module.exports.xiaoming = function(){console.log("xiaoming!");}
module.exports.xiaohua = function(){console.log("xiaohua!");}
module.exports.xiaolei = function(){console.log("xiaohua!");}
//main.js
var result= require("./hello");
console.log(result);
/*结果
{ word: [Function],
hello: [Function],
xiaoming: [Function],
xiaohua: [Function],
xiaolei: [Function] }
*/
result.hello();//hello
result.world();//world
result.xiaohua();//xiaohua