且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Windows 上的 npm 脚本中使用变量

更新时间:2023-09-01 15:58:46

所以,我链接的答案工作,由于操作系统的不同,似乎在我的机器上失败了.

So, the answer I linked which was not working, seemed to fail on my machine because of a difference in operating systems.

这适用于 Linux:

This works on Linux:

"new_project": "git clone x:/parent_repo $PROJECT & cd $PROJECT & git clone x:/child_repo"

PROJECT=new_project_name npm run new_project

要使其在 Windows 上运行,您需要使用 % % 而不是 $ 对变量进行转义.您还需要在 windows cli 上专门设置变量.要与脚本结合,需要用&&链接脚本和设置变量命令.

To get this to work on Windows, you need to escape the variable with % % in stead of $. Also you need to specificaly SET the variable on the windows cli. To combine with the script, you need to link the script and the set variable command with &&.

所以上面在 Windows 上变成了:

So the above on Windows becomes:

"new_project": "git clone x:/parent_repo %PROJECT% & cd %PROJECT% & git clone x:/child_repo"

SET PROJECT=new_project_name &&npm run new_project

另请注意,如果您想引用配置变量,您必须以相同的方式转义该变量.所以 $npm_package_config_yourvariable 在 Windows 上变成了 %npm_package_config_yourvariable%.

Also note, if you want to refer to the config variables you have to escape that variable in the same way. So $npm_package_config_yourvariable becomes %npm_package_config_yourvariable% on Windows.