let a = require('./a.js')
执行被加载模块中的代码
得到被加载的模块中的exports赋值到a变量上
exports
node中的模块作用域,默认文件中的所有成员只在当前文件模块有效
对于希望可以被其他模块访问的成员,可以通过把这些成员挂载到exports这个接口对象上
exports是一个对象,每个js文件中都有这么一个对象,默认为空对象
console.log(exports) // 输出 {}
exports对象添加一个方法,属性名为add
// a.js
let add = function(x, y){
return x + y
}
exports.add = add
导入a.js文件,即导入了a.js文件中exports对象,如果a.js文件exports不导出任何内容,那么b.js文件中的add变量为空对象
// b.js
let add = require('./a')
console.log(add) // 输出 { add: [Function: add] }
有时我们需要导出的是一个函数,数组,变量而不是一个对象,可以使用module.exports
注意当导入某个文件时,会先执行这个文件里面的内容,如导入a.js时会执行console.log(exports)
// a.js
let add = function (x, y) {
return x + y
}
console.log(exports)
module.exports = add
// b.js
let add = require('./a')
console.log(add) // 输出 [Function: add]
覆盖
let a = 'aaa'
let b = 'bbb'
exports.a = a
// module.exports会覆盖前面的exports
module.exports = b
覆盖原理
// 底层原理
module = {
exports:{}
}
return module.export
所以
console.log(exports === module.exports) // true
exports其实是module.exports的引用,所以会覆盖
注意引用这两个字,module.exports和exports都指向同一个对象,这里涉及js指针原理
// 导出多个成员
export.a = 'aaa'
export.b = 'bbb'
或
module.exports = {
export.a = 'aaa'
export.b = 'bbb'
}
// 导出单个成员
module.exports = 'aaa'
require方法加载规则
优先从缓存加载
核心模块
路径形式的文件模块
第三方模块
优先从缓存加载,比如main.js中加载a.js和b.js,而a.js中加载b.js,当main.js执行到加载b.js时,发现b.js已被a.js加载,就不会重新加载b.js,而是从缓存中取出
第三方模块加载方式:
先找当前文件目录下的node_modules/art-template/package.json中的main属性
找不到会找备用选项:node_modules/art-template下的index.js文件
还是没有会查找上级的node_modules文件夹,再找不到会层层往上找,磁盘根目录还找不到会报错 can‘t find module xxx
npm使用
npm init 初始化package.json文件
npm init -y 跳过想到,快速初始化
npm i art-template --save 安装并在dependencies保存依赖
npm un art-template --save 卸载并去除依赖
npm config list npm配置目录
安装淘宝镜像,cnpm install
npm install -g cnpm --registry=https://registry.npm.taobao.org
不想使用cnpm但想使用淘宝镜像,可以配置npm的config,这样还是可以使用npm来安装包
npm config set registry https://registry.npm.taobao.org