什么是模块化
特性
- 将程序划分为一个个小的结构
- 每个结构编写自己的逻辑代码,有自己的作用域
- 暴露自己模块中变量、对象、函数
- 导入其他模块中的变量、对象、函数
规范
AMD
CMD
CommonJS
CommonJS
node中实现模块化的方式是CommonJS,导入模块是同步
特点:
- 每个js文件都是单独的模块
- 可以导入导出,导出使用
exports
或者module.exports
,导入使用require
exports
exports是一个对象,我们可以在这个对象中添加很多个属性,添加的属性会导出
//bar.js
const name ='jae'
const age = 18
exports.name = name
exports.age = age
另外一个文件中可以导入:
//main.js
const bar = require('./bar')
console.log(bar.name);//jae
console.log(bar.age);//18
注意事项
导入的exports 对象是引用值,在main.js 中修改,bar.js中也会被修改
//bar.js
const name ='jae'
const age = 18
exports.name = name
exports.age = age
setTimeout(()=>{
console.log('2s后打印bar中的exports.name',exports.name);
},2000)
const bar = require('./bar')
console.log('main.js中的bar',bar.name);
setTimeout(()=>{
bar.name = 'hhh'
console.log('1s后修改main.js中的bar',bar.name);
},1000)
控制台输出
module.exports
Node中我们经常导出东西的时候,又是通过module.exports导出的
node 中默认module.exports = exports
require
导入格式如下:require(X)
情况一:X是一个核心模块,比如path、http
规则:直接返回核心模块,并且停止查找
情况二:X是以 ./ 或 …/ 或 /(根目录)开头的
规则:
- 如果有后缀名,按照后缀名的格式查找对应的文件
- 如果没有后缀名,会按照如下顺序:
- 直接查找文件X
- 查找X.js文件
- 查找X.json文件
- 查找X.node文件
- 如果没有找到,那么报错:not found
情况三:
直接是一个X(没有路径),并且X不是一个核心模块
- 在
E:\ZYH\node\node\base\CommonJS\main.js
编写 require(bar) - 查找bar的顺序如下:
paths: [
‘e:\ZYH\node\node\base\CommonJS\node_modules’,
‘e:\ZYH\node\node\base\node_modules’,
‘e:\ZYH\node\node\node_modules’,
‘e:\ZYH\node\node_modules’,
‘e:\ZYH\node_modules’,
‘e:\node_modules’
]