require
本文是讲关于如何在node中使用require。
一、历史渊源
require时代的模块
node编程中最重要的思想之一就是模块,而正是这个思想,让JavaScript的大规模工程成为可能。模块化编程在js界流行,也是基于此,随后在浏览器端,requirejs和seajs之类的工具包也出现了,可以说在对应规范下,require统治了ES6之前的所有模块化编程,即使现在,在ES6 module被完全实现之前,还是这样。node的module遵循CommonJS规范,requirejs遵循AMD,seajs遵循CMD,虽各有不同,但总之还是希望保持较为统一的代码风格,ES6之后可以使用import 导入export导出,但还是得看当前的node版本是否支持该功能。
名称 | 规范 | 用途 |
---|---|---|
node require | CommonJS | node后端 |
requirejs | AMD | web前端 |
seajs | CMD | web前端 |
二、require的使用
首先所有的文件都运行在node环境中同一个目录。
1.导出单个函数
假设我们要制作一个模块,要导出一个函数:
//a.js
function hello(){
console.log('hi! I am a.js')
}
module.exports = hello //导出的函数
当要应用这个模块的时候
//index.js
let hello = require("./a.js")
hello() //调用模块中函数,运行结果: hi! I am a.js
这样就导出函数hello最终module.eports是一个作为被导出的对象,一个模块只有一个导出对象module.exports,那么如何导出多个函数呢?聪明的你可能已经想到了,可以把多个方法放在同一个对象中。
2.导出多个函数
导出多个函数
//a.js
function hello1(){
console.log('hi! I am a1.js')
}
function hello2(){
console.log('hi! I am a2.js')
}
module.exports.hello1 = hello1
module.exports.hello2 = hello2
使用多个函数
let foo = require("./a") //.js可以被省略
foo.hello1()
foo.hello2()
$ node index.js
hi! I am a1.js
hi! I am a2.js
3.exports与module.exports
也许你也见过这种写法
//a.js
function hello(){
console.log('hi! I am a.js')
}
exports = hello //导出的函数
这样也可以,在一个node执行一个文件时,会给这个文件内生成一个 exports
和module
对象,而module
又有一个exports
属性。他们之间的关系如下图,都指向一块{}内存区域。
exports = module.exports = {};
但是最终被模块所采用的是module.exports
//a.js
function hello(){
console.log('hi! I am a.js')
}
exports.hello = hello;
exports = '指向其他内存区'; //这里把exports的指向指走
//index.js
var hello = require('/a.js');
hello() //结果为 hi! I am a.js
刚开始exports与module.exports指向同一内存,exports.hello改变使得module.export也发生改变,随后exports改变了指向对象,但最终模块读取的是module.exports指向的那块内存
参考资料:
https://blog.youkuaiyun.com/qq_28702545/article/details/54892562