如何让 npm script 串行?
在使用 npm script 时,默认情况下,多个命令是并行执行的,这可能导致某些依赖关系问题。为了确保命令按顺序执行,我们可以采用以下几种方法。
1. 使用 && 符号
最直接的方式是使用 && 符号将命令串联在一起。只有前一个命令成功执行后,才会执行下一个命令。
{
"scripts": {
"build": "npm run clean && npm run compile && npm run minify"
}
}
在这个例子中,只有当 npm run clean 成功时,才会执行 npm run compile,随后再执行 npm run minify。
2. 使用 npm-run-all
npm-run-all 是一个非常实用的工具,它可以帮助我们以串行或者并行的方式运行多个 npm script。安装这个工具:
npm install npm-run-all --save-dev
然后在 package.json 中使用 npm-run-all:
{
"scripts": {
"clean": "echo clean",
"compile": "echo compile",
"minify": "echo minify",
"build": "npm-run-all --serial clean compile minify"
}
}
在这个例子中,npm-run-all --serial 将确保 clean、compile 和 minify 按顺序执行。
3. 使用 await 和 async
如果你在 npm script 中使用 JavaScript 文件,可以利用 async 和 await 来实现串行执行。在这种情况下,你可以创建一个 JavaScript 文件,使用 Node.js 的 child_process 模块来执行命令:
// build.js
const { exec } = require('child_process');
const runCommand = (command) => {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
return;
}
console.log(stdout);
resolve(stdout);
});
});
};
const build = async () => {
try {
await runCommand('npm run clean');
await runCommand('npm run compile');
await runCommand('npm run minify');
} catch (error) {
console.error('Error executing build:', error);
}
};
build();
然后在 package.json 中调用这个脚本:
{
"scripts": {
"clean": "echo clean",
"compile": "echo compile",
"minify": "echo minify",
"build": "node build.js"
}
}
4. 使用 concurrently 和 --success first
如果你需要在执行多个命令时只关注第一个成功的命令,可以使用 concurrently。首先,安装 concurrently:
npm install concurrently --save-dev
然后在 package.json 中配置:
{
"scripts": {
"clean": "echo clean",
"compile": "echo compile",
"minify": "echo minify",
"build": "concurrently --success first \"npm run clean\" \"npm run compile\" \"npm run minify\""
}
}
总结
在 npm script 中实现串行执行的方法有多种选择,最常见的方法是使用 && 符号。对于更复杂的需求,可以使用 npm-run-all、async/await 或 concurrently 来实现更灵活的控制。选择合适的方法可以确保你的构建过程高效且没有错误。