scripts
2023年07月27日
一、认识
package.json scripts
定义可执行的命令脚本。这些脚本通常用于构建、测试、启动等任务,或者可以在命令行中通过 npm run <script-name>
执行。
二、语法
{
"scripts": {
"start": "node app.js",
"test": "jest"
}
}
三、场景
3.1 配置环境变量
通过原生指令配置
-
Mac
系统配置: 通过export
配置"scripts": {
"publish-mac": "export NODE_ENV=prod webpack -p --progress --colors",
} -
Win
系统配置: 通过set
配置"scripts": {
"publish-win": "set NODE_ENV=prod webpack -p --progress --colors"
}
通过 cross-env
依赖配置
cross-env
是运行跨平台设置和使用环境变量的脚本。使得您可以使用单个命令,而不必担心为平台正确设置或使用环境变量。
-
安装
cross-env
:yarn add cross-env
-
配置
cross-env
:细节cross-env
后面紧跟命令即可,不需要加&
或者&&
修饰
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
}
} -
使用环境变量:
const env = process.env.NODE_ENV;
3.2 配置执行单条命令
-
运行单个
.sh
脚本文件"scripts": {
"serve": "vuepress dev .",
"build": "vuepress build . ",
"start":"sh start.sh",
"update":"sh push.sh",
"publish":"sh deploy.sh",
"fix-memory-limit": "cross-env LIMIT=409600 increase-memory-limit"
}, -
运行单个
JavaScript
文件{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node src/app.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
3.3 配置执行多条命令
通过 &
运算符同时(并行)执行多条命令
-
并行运行多个
npm
命令{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npm run build & npm run server",
"server": "nodemon --watch build node build/app.js",
"build": "webpack --config ./config/webpack.config.js --watch"
},
"keywords": [],
"author": "",
"license": "ISC"
} -
并行运行多个
JavaScript
文件{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node src/app1.js & node src/app2.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
通过 &&
运算符顺序(串行)执行多条命令
-
串行运行多个
JavaScript
文件{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node src/app1.js && node src/app2.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
通过 npm-run-all
(可配置化)执行多条命令
-
并行执行多条
npm
命令{
"name": "day1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev":"npm-run-all --parallel dev:**",
"dev:build": "webpack --config webpack.server.js --watch",
"dev:start": "nodemon --watch build --exec node build/bundle.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"koa": "^2.13.4",
"koa-router": "^10.1.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"webpack": "^5.58.2",
"webpack-cli": "^4.9.1",
"webpack-node-externals":"^1.7.2"
}
}
四、原理
npm
脚本的原理非常简单。每当执行npm run
,就会自动新建一个Shell
,在这个Shell
里面执行指定的脚本命令。因此,只要是Shell
(一般是 Bash)可以运行的命令,就可以写在 npm
脚本里面。