如何在 npm 脚本中引用包版本? [英] How can I reference package version in npm script?
问题描述
我想在 npm 脚本中引用我的包版本,以便我可以在应用程序中显示当前版本.类似的东西
I want to reference my package version in a npm script so I can show current version in the app. Something like
{
"name": "bla",
"version": "1.0.0",
"author": "bla bla",
"scripts": {
"build": "node VERSION=<<package.version>> build/build.js"
}
}
有没有办法做到这一点?
Is there a way to do this?
推荐答案
1) 在 npm-scripts 中引用包版本.
在 npm-script
中,您可以使用变量 npm_package_version
引用 version
.例如:
1) Referencing package version in npm-scripts.
In npm-script
's you can reference the version
using the variable npm_package_version
. For example:
使用 bash shell(例如 Linux、macOS):
{
...
"version": "1.0.0",
"scripts": {
"build": "echo $npm_package_version"
}
}
注意$
前缀
使用 Windows(例如 cmd.exe、Powershell):
{
...
"version": "1.0.0",
"scripts": {
"build": "echo %npm_package_version%"
}
}
注意%
前缀和后缀
跨平台
要跨平台使用一种语法,请查看包cross-var
To utilize one syntax cross-platform check out the package cross-var
也可以在您的应用程序/节点脚本(即 build.js
)中引用包版本,如下所示:
The package version can also be referenced in your a app/node script (i.e. build.js
) as follows:
const VERSION = process.env.npm_package_version;
console.log(VERSION); // --> 1.0.0
<小时>
3) 用包版本替换 .js 文件中的占位符字符串.
实现此目的的另一种方法是在您的 JavaScript 文件中指定一个占位符文本字符串.假设我们有一个名为 build.js
的文件,在该文件中,我们有一个名为 VERSION
的变量,声明如下:
3) Replacing a placeholder string in a .js file with package version.
Another way to achieve this is to specify a placeholder text string within your JavaScript file. Lets say we have a file named build.js
and within that file we have a variable named VERSION
declared as follows:
// build.js
const VERSION = '@VERSION@'
如您所见,占位符文本字符串是 @VERSION@
.
As you can see, the placeholder text string is @VERSION@
.
然后,您可以在 npm-script 如下:
You can then install and utilize the package called replace in an npm-script as follows:
{
...
"version": "1.0.0",
"scripts": {
"add-version": "replace -s "@VERSION@" $npm_package_version build/build.js"
}
}
运行 npm run add-version
会将 @VERSION@
的实例替换为包版本(即 1.0.0
),在名为 build.js
的文件.此解决方案会将 npm 包版本硬编码到生成的文件中.
Running npm run add-version
will replace the instance of @VERSION@
with the package version (i.e. 1.0.0
), in the file named build.js
. This solution will hard-code the npm package version into the resultant file.
注意:add-version
脚本(上面)中的 to 字符串当前使用 $
前缀(即 $npm_package_version
) 来访问变量,所以这只会在 bash shell 上成功运行.但是,对于跨平台使用,您需要使用 cross-var
如第一部分(以上)中所述.在这种情况下,add-version
脚本可以定义如下:
Note: The to string in the add-version
script (above) currently uses the $
prefix (i.e. $npm_package_version
) to access the variable, so this will only run successfully on a bash shell. However, for cross-platform usage you'll need to use cross-var
as explained in section one (above). In which case the add-version
script can be defined as follows:
{
...
"version": "1.0.0",
"scripts": {
"add-version": "cross-var replace -s "@VERSION@" $npm_package_version build/build.js"
}
}
这篇关于如何在 npm 脚本中引用包版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!