Ben*_*arp 1 command-line npm npm-scripts
在 NPM 项目中,我想为每个构建版本提交一个提交。这将使我能够返回到当前的构建版本,修复错误,而无需通过新版本的所有 QA。
我们可以使用这样的 npm 脚本进行提交(请参阅此答案):
包.json
"scripts": {
"git": "git add . && git commit -m",
}
Run Code Online (Sandbox Code Playgroud)
然后通过运行来调用脚本:
npm run git -- "Message of the commit"
Run Code Online (Sandbox Code Playgroud)
我想在 npm run build 之后自动运行它。为此,我们可以创建一个新命令。
包.json
npm run git -- "Message of the commit"
Run Code Online (Sandbox Code Playgroud)
这可以使用运行 npm run buildAndCommit -- "commit for a new build"
唯一剩下的就是我想将此提交标识为可以链接到提交的提交。是否可以使用“ BUILD -”自动启动消息并将在命令行中传递的唯一消息添加到该消息中?就像是:
包.json
"scripts": {
"buildAndCommit": "npm run build && git add . && git commit -m",
}
Run Code Online (Sandbox Code Playgroud)
如果无法在package.json 中对字符串进行模板化,我如何使用命令行脚本来实现它?(Powershell 是我的命令行工具)。
在*nix平台上,npmsh默认使用来执行 npm 脚本。在这种情况下,您可以简单地使用shell 函数并使用$1 位置参数引用通过 CLI 传递的 git 消息参数。
你的 npm 脚本会像这样重新定义:
"scripts": {
"build": "...",
"buildAndCommit": "func() { npm run build && git add . && git commit -m \"BUILD - $1\"; }; func"
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,通过 Windows Powershell 解决方案并不那么简单和简洁。
使用 Powershell 时,npmcmd默认使用执行 npm 脚本。同样cmd,默认情况下npm 也通过其他 Windows 控制台使用,例如Command Prompt。
实现您的要求的一种方法是通过您的 npm 脚本调用 node.js。下面提供了两种基本相同的不同方法。两者都将成功跨平台运行(在您的情况下通过 Powershell)。
方法 A - 使用单独的 node.js 脚本
创建以下 node.js 脚本。让我们将文件命名为script.js并将其保存在项目目录的根目录中,即package.json所在的同一目录中。
脚本.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] });
Run Code Online (Sandbox Code Playgroud)
解释
node.js 内置程序process.argv在索引 2 处捕获参数,即通过 CLI 提供的 git commit 消息。git commit 消息与子字符串连接BUILD -以形成所需的提交消息。结果字符串分配给变量mssg。
然后我们利用内置的 node.jsexecSync()来执行给定的 npm 脚本。如您所见,mssg变量的值用作 git commit 消息。
该stdio选项是用于确保管道,即正确的配置stdin,stdout“标准错误”,在父进程和子进程之间建立。
定义您的 npm 脚本,命名buildAndCommit如下:
包.json
"scripts": {
"build": "...",
"buildAndCommit": "node script"
}
Run Code Online (Sandbox Code Playgroud)
以上node调用script.js.
方法 B - 在 npm 脚本中内联 node.js 脚本
或者,上述 node.js 脚本(即script.js)可以在您的 npm 脚本中内联提供 - 因此否定使用单独的.js文件。
包.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] })\""
}
Run Code Online (Sandbox Code Playgroud)
这使用了方法 A 中的相同代码,尽管它略有重构。显着的差异是:
-e用于评估内联 JavaScript。process.argv 这次将在参数数组的索引 1 处捕获参数,即 git commit 消息。\\\"运行 npm 脚本
根据需要使用方法 A或方法 B通过 CLI 运行命令:例如:
$ npm run buildAndCommit -- "commit for a new build"
Run Code Online (Sandbox Code Playgroud)
这将产生以下 git commit 消息:
BUILD - commit for a new build
| 归档时间: |
|
| 查看次数: |
2404 次 |
| 最近记录: |