运行
// 安装nodemon
npm i nodemon -g
// 运行 监听代码
nodemon .\02-url.js
// 安装node-dev
npm i node-dev -g
// 运行 监听代码
node-dev .\02-url.js
以上两个工具都需要全局安装,效果一样
模块,包,commonJS规范
将公共的功能抽离成单独的js文件做为一个模块,默认该模块的方法或属性无法被外部访问,如果访问就必须通过exports或者module.exports暴漏属性或者方法.
暴露方法1
//导出使用方法:
function add(a,b) {
return a+b;
}
let a1 = 1
module.exports = {add,a1};
module.exports = {a:1};
module.exports .a = 1
module.exports = function(name,age,money) {
this.name = name;
this.age = age;
this.money = money;
this.say = function() {
console.log('我的名字叫:'+this.name+',我今年'+this.age+'岁,月薪为:'+this.money+'元;')
}
};
//导入使用方法
let req = require ('../app.js');
console.log(req.a1,req.a)
const {add,a1} = require('../app.js')
暴露方法2
// 模块中
let name = 123
function say() {
console.log(name)
}
// exports.变量名 = 需要导出的属性或者方法
exports.a = say
// exports 是module.exports的一个引用,可以认为是 var exports = module.exports
ES6 导入导出
在package.json中开启ES6模块化
// 模块中
const fun = () => {
console.log('方法')
}
const muduleA = {
fun
}
export default muduleA
// 导入
import muduleA from "./commonJs.js"; // 一定要写完整的文件名,需要带后缀
console.log(muduleA.fun())
npm的使用
init初始
npm i ** -g // 全局安装
全局安装不会在package.json中留下记录