在NPM项目中,我想为每个构建版本进行一次提交。这将使我能够返回到当前的构建版本,修复错误,而不必经历新版本的所有质量检查。
我们可以使用如下(see this answer)这样的npm脚本进行提交:
package.json
"scripts": {
"git": "git add . && git commit -m",
}
然后通过运行以下命令来调用脚本:
npm run git -- "Message of the commit"
我想将其自动化以在npm run build之后运行。为此,我们可以创建一个新命令。
package.json
"scripts": {
"buildAndCommit": "npm run build && git add . && git commit -m",
}
这可以使用npm run buildAndCommit -- "commit for a new build"
剩下的唯一一件事就是我想将此提交标识为可以链接到一个提交的提交。是否可以使用“ BUILD -
”自动启动消息,并添加在命令行中传递的唯一消息?像这样:
package.json
"scripts": {
"buildAndCommit": "npm run build && git add . && git commit -'Build' + $uniqueMessageFromTheCommandLine`",
}
如果无法在 package.json 中对字符串进行模板化,如何使用命令行脚本实现呢? (Powershell是我的命令行工具)。
答案 0 :(得分:1)
在 * nix 平台上,npm默认使用sh
来执行npm脚本。在这种情况下,您可以简单地使用shell function并使用$1
positional parameter引用通过CLI传递的git消息参数。
您的npm脚本将被这样重新定义:
"scripts": {
"build": "...",
"buildAndCommit": "func() { npm run build && git add . && git commit -m \"BUILD - $1\"; }; func"
}
不幸的是,通过Windows Powershell,该解决方案并不那么简单和简洁。
在使用Powershell时,npm默认使用cmd
执行npm脚本。同样,npm默认也会通过其他Windows控制台使用cmd
,例如 Command Prompt 。
一种满足您要求的方法是通过npm脚本调用node.js。以下提供了两种基本相同的不同方法。两种都可以成功运行跨平台(在您的情况下是通过Powershell)。
方法A-使用单独的node.js脚本
创建以下node.js脚本。我们将文件命名为 script.js 并将其保存在项目目录的根目录中,即 package.json 所在的目录中。
script.js
const execSync = require('child_process').execSync;
const mssg = 'BUILD - ' + process.argv[2];
execSync('npm run build && git add . && git commit -m \"' + mssg + '\"', { stdio:[0, 1, 2] });
说明
内置process.argv
的node.js捕获通过CLI提供的索引2处的参数,即git commit消息。 git commit消息与子字符串BUILD -
并置以形成所需的提交消息。结果字符串分配给变量mssg
。
然后我们使用内置的execSync()
的node.js执行给定的npm脚本。如您所见,mssg
变量的值用作git commit消息。
使用stdio
选项可确保在父进程与子进程之间建立正确的管道配置,即stdin
,stdout
,“ stderr”。
定义您的名为buildAndCommit
的npm脚本,如下所示:
package.json
"scripts": {
"build": "...",
"buildAndCommit": "node script"
}
在node
之上调用script.js
。
方法B-在npm脚本中内联node.js脚本
或者,可以在npm脚本中内联提供上述的node.js脚本(即 script.js ),因此可以避免使用单独的.js
文件。
package.json
"scripts": {
"build": "...",
"buildAndCommit": "node -e \"const mssg = 'BUILD - ' + process.argv[1]; require('child_process').execSync('npm run build && git add . && git commit -m \\\"' + mssg + '\\\"', { stdio:[0, 1, 2] })\""
}
此方法使用了方法A 中的相同代码,尽管它进行了稍微的重构。显着的区别是:
-e
用于评估嵌入式JavaScript。process.argv
这次将在参数数组的索引1处捕获参数,即git commit消息。\\\"
运行npm脚本
根据需要,使用方法A 或方法B 通过CLI运行命令:例如:
$ npm run buildAndCommit -- "commit for a new build"
这将产生以下git commit消息:
BUILD - commit for a new build