本文作者: jsweibo
本文链接: https://jsweibo.github.io/2019/05/05/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3npm%E8%84%9A%E6%9C%AC/
摘要
本文主要讲述了:
- 环境变量
- 特殊的 npm 脚本
正文
环境变量
npm run-script命令会把一些额外变量注入环境变量。
Path
示例:
1 | { |
learn_npm/index.js
1 | console.log(process.env.Path); |
运行:
1 |
|
package.json
npm run-script命令会把package.json里的字段加上npm_package_前缀注入process.env对象中。
示例:
1 | { |
learn_npm/index.js
1 | console.log(process.env.npm_package_name); |
运行:
1 |
|
输出:
1 | learn_npm |
npm 全局配置
npm run-script命令会把 npm 全局配置里的字段加上npm_config_前缀注入process.env对象中。
示例:
1 | { |
learn_npm/index.js
1 | console.log(process.env.npm_config_registry); |
运行:
1 |
|
输出:
1 | https://registry.npmmirror.com/ |
npm_lifecycle_event
npm run-script命令会把npm_lifecycle_event变量注入process.env对象中。
npm_lifecycle_event变量标志了当前执行的脚本名称。
示例:
1 | { |
learn_npm/index.js
1 | console.log(process.env.npm_lifecycle_event); |
运行:
1 |
|
输出:
1 | dev |
特殊的 npm 脚本
env 脚本
env脚本是特殊的内建命令,默认用于罗列运行时中可用的环境变量。
如果开发者自己定义了env脚本,就以开发者定义的为准。
1 |
|
直接运行脚本
npm run-script startnpm run-script stopnpm run-script restartnpm run-script test
调用上面 4 个脚本的时候可以省略run-script,就像这样:
npm startnpm stopnpm restartnpm test
脚本前缀
脚本前缀一共有 2 个:
- pre
- post
示例:
1 | { |
当开发者运行npm run-script dir时,npm 会依次执行:
- predir
- dir
- postdir
start 脚本
如果没有定义start脚本,且当前项目的根目录下存在server.js文件,则
1 |
|
或
1 |
|
相当于
1 |
|
install 脚本
特别注意:npm install不仅会安装依赖,还会执行install脚本,而npm run-script install只会执行install脚本。
install脚本会在两个时候执行:
- 包运行
npm install的时候 - 包被安装的时候(作为依赖)
install脚本的执行顺序:
preinstallinstallpostinstall
此外,install脚本还有默认行为:
如果没有定义install脚本或preinstall脚本,且当前项目的根目录下存在binding.gyp文件,则
1 |
|
或
1 |
|
相当于
1 |
|
uninstall 脚本
包被卸载的时候(作为依赖)会运行uninstall脚本。
uninstall脚本的执行顺序:
preuninstalluninstallpostuninstall
restart 脚本
如果没有定义restart脚本,则
1 |
|
或
1 |
|
相当于依次执行:
- prerestart
- prestop
- stop
- poststop
- prestart
- start
- poststart
- postrestart
如果定义了restart脚本,则
1 |
|
或
1 |
|
相当于依次执行:
- prerestart
- restart
- postrestart
参考资料
本文作者: jsweibo
本文链接: https://jsweibo.github.io/2019/05/05/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3npm%E8%84%9A%E6%9C%AC/
本文对你有帮助?请支持我
- 本文链接: https://jsweibo.github.io/2019/05/05/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3npm%E8%84%9A%E6%9C%AC/
- 版权声明: 除非另有说明,否则本网站上的内容根据署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。