Zby*_*nek 104 version package.json angular
如何在angular2应用程序中显示应用程序版本?该版本应从package.json文件中获取
{
"name": "angular-app",
"version": "0.0.1",
...
}
Run Code Online (Sandbox Code Playgroud)
在角1.x,我有这个HTML:
<p><%=version %></p>
Run Code Online (Sandbox Code Playgroud)
在angular2中,这不会呈现为版本号,而是按原样(<%=version %>而不是0.0.1)打印.
rad*_*eit 181
如果您正在使用Angular CLI并希望在环境变量中拥有该版本,则可以在您的环境中编写.
"compilerOptions": {
...
"resolveJsonModule": true
...
Run Code Online (Sandbox Code Playgroud)
在您的组件中:
import { version } from '../../package.json';
...
export class AppComponent {
public version: string = version;
}
Run Code Online (Sandbox Code Playgroud)
如果你得到了
找不到名字'要求'
错误,请更改您的/tsconfig.json(不在/src/tsconfig.app.json根文件夹中)以包含节点类型:
"compilerOptions": {
...
"resolveJsonModule": true
...
Run Code Online (Sandbox Code Playgroud)
您还需要安装@ types/node
import { version } from '../../package.json';
...
export class AppComponent {
public version: string = version;
}
Run Code Online (Sandbox Code Playgroud)
Dys*_*cuk 46
如果您使用的是webpack或angular-cli(使用webpack),您只需要在组件中使用package.json并显示该prop.
const { version: appVersion } = require('../../package.json')
// this loads package.json
// then you destructure that object and take out the 'version' property from it
// and finally with ': appVersion' you rename it to const appVersion
Run Code Online (Sandbox Code Playgroud)
然后你有你的组件
@Component({
selector: 'stack-overflow',
templateUrl: './stack-overflow.component.html'
})
export class StackOverflowComponent {
public appVersion
constructor() {
this.appVersion = appVersion
}
}
Run Code Online (Sandbox Code Playgroud)
Vam*_*msi 19
尝试DyslexicDcuk的答案导致了 cannot find name require
然后,阅读https://www.typescriptlang.org/docs/handbook/modules.html中的 "可选模块加载和其他高级加载方案"部分帮助我解决了这个问题.(Gary在这里提到/sf/answers/2923723561/)
使用以下声明来要求package.json.
declare function require(moduleName: string): any;
const {version : appVersion} = require('path-to-package.json');
Run Code Online (Sandbox Code Playgroud)
Ion*_*aru 14
使用tsconfig选项,--resolveJsonModule您可以在Typescript中导入json文件。
在environment.ts文件中:
import { version } from '../../package.json';
export const environment = {
VERSION: version,
};
Run Code Online (Sandbox Code Playgroud)
您现在可以environment.VERSION在您的应用程序中使用。
Ste*_*eve 11
在 Angular 12 中import { version } from '../../package.json';出现错误:
./src/environments/environment.ts:10:13-20 - 错误:不应从默认导出模块导入命名导出“版本”(作为“版本”导入)(很快将仅提供默认导出)
要继续导入版本而不会将 package.json 的全部内容引入构建中而产生安全影响,您可以执行以下操作:
export const environment = {
...
VERSION: require('../../package.json').version,
};
Run Code Online (Sandbox Code Playgroud)
来自https://github.com/angular/angular-cli/issues/3770#issuecomment-269822722
如果遇到Cannot find name 'require'错误,请参阅/sf/answers/3019087081/和/sf/answers/3780348561/
打字稿
import { Component, OnInit } from '@angular/core';
declare var require: any;
@Component({
selector: 'app-version',
templateUrl: './version.component.html',
styleUrls: ['./version.component.scss']
})
export class VersionComponent implements OnInit {
version: string = require( '../../../../package.json').version;
constructor() {}
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="row">
<p class="version">{{'general.version' | translate}}: {{version}}</p>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 7
针对cli用户的简化列表解决方案。
添加declare module '*.json';上src/typings.d.ts
然后src/environments/environment.ts:
import * as npm from '../../package.json';
export const environment = {
version: npm.version
};
Run Code Online (Sandbox Code Playgroud)
完成:)
这个答案特定于 Angular 12+。它使用 Webpack 5。
新规范不支持这一点,您将收到警告。代替:
import { version } from './your-path/package.json';
console.log(version);
Run Code Online (Sandbox Code Playgroud)
使用:
import pkg from './your-path/package.json';
console.log(pkg.version);
Run Code Online (Sandbox Code Playgroud)
此外,您还必须在tsconfig.json中提供
"compilerOptions": {
...
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
...
Run Code Online (Sandbox Code Playgroud)
声明version为环境变量是个好主意所以你可以在项目的任何地方使用它.(特别是在加载基于版本缓存的文件的情况下e.g. yourCustomjsonFile.json?version=1.0.0)
为了防止出现安全问题(如@ZetaPR所述),我们可以使用这种方法(在@sgwatgit的注释中)
简而言之:我们创建一个yourProjectPath\PreBuild.js文件.像这样:
const path = require('path');
const colors = require('colors/safe');
const fs = require('fs');
const dada = require.resolve('./package.json');
const appVersion = require('./package.json').version;
console.log(colors.cyan('\nRunning pre-build tasks'));
const versionFilePath = path.join(__dirname + '/src/environments/version.ts');
const src = `export const version = '${appVersion}';
`;
console.log(colors.green(`Dada ${colors.yellow(dada)}`));
// ensure version module pulls value from package.json
fs.writeFile(versionFilePath, src, { flat: 'w' }, function (err) {
if (err) {
return console.log(colors.red(err));
}
console.log(colors.green(`Updating application version
${colors.yellow(appVersion)}`));
console.log(`${colors.green('Writing version module to
')}${colors.yellow(versionFilePath)}\n`);
});
Run Code Online (Sandbox Code Playgroud)
上面的代码片段将创建一个新文件/src/environments/version.ts,其中包含一个名为的常量version,并通过package.json文件中的提取值进行设置.
为了运行PreBuild.json构建的内容,我们将此文件添加到Package.json- > "scripts": { ... }"部分,如下所示.所以我们可以使用以下代码运行项目npm start:
{
"name": "YourProject",
"version": "1.0.0",
"license": "...",
"scripts": {
"ng": "...",
"start": "node PreBuild.js & ng serve",
},...
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以简单地导入版本并在任何我们想要的地方使用它:
import { version } from '../../../../environments/version';
...
export class MyComponent{
...
public versionUseCase: string = version;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我尝试以一种不同的方式解决这个问题,同时考虑到易用性和可维护性。
我使用 bash 脚本来更改整个应用程序的版本。以下脚本将询问您所需的版本号,并且该版本号适用于整个应用程序。
#!/bin/bash
set -e
# This script will be a single source of truth for changing versions in the whole app
# Right now its only changing the version in the template (e.g index.html), but we can manage
# versions in other files such as CHANGELOG etc.
PROJECT_DIR=$(pwd)
TEMPLATE_FILE="$PROJECT_DIR/src/index.html"
PACKAGE_FILE="$PROJECT_DIR/package.json"
echo ">> Change Version to"
read -p '>> Version: ' VERSION
echo
echo " #### Changing version number to $VERSION #### "
echo
#change in template file (ideally footer)
sed -i '' -E "s/<p>(.*)<\/p>/<p>App version: $VERSION<\/p>/" $TEMPLATE_FILE
#change in package.json
sed -i '' -E "s/\"version\"\:(.*)/\"version\"\: \"$VERSION\",/" $PACKAGE_FILE
echo; echo "*** Mission Accomplished! ***"; echo;
Run Code Online (Sandbox Code Playgroud)
我已将此脚本保存在项目根目录中名为version-manager.sh的文件中,并且在我的 package.json 文件中,我还创建了一个脚本以在需要修改版本时运行它。
"change-version": "bash ./version-manager.sh"
Run Code Online (Sandbox Code Playgroud)
最后,我可以通过执行来更改版本
npm run change-version
Run Code Online (Sandbox Code Playgroud)
此命令将更改 index.html 模板以及 package.json 文件中的版本。以下是从我现有的应用程序中截取的一些屏幕截图。
这个https://github.com/angular/angular-cli/issues/5190有一个有趣的解决方案,使用 shell 文件生成 version.ts 文件。@sanjeev 在这个论坛上有类似的解决方案。
该解决方案使用 Node、javascript 和 fs 模块来实现相同的目的。肯定可以在linux下工作。在 Windows 中应该可以正常工作,因为 Node/fs 是跨平台的......对吗?
在 package.json 添加一行:
{
"version": "0.0.1",
...
"scripts": {
"version": "node gen_version.js $npm_package_version",
...
},
...
}
Run Code Online (Sandbox Code Playgroud)
创建 gen_version.js (注意:它不是打字稿)
var fs = require('fs');
// arg[0]: node path
// arg[1]: this script's path
// arg[2]: 1st arg on command line
console.log('current version: ' + process.argv[2])
path = 'src/environments/version.ts'
script = 'export class Constants {'
script += ' static readonly version = \'' + process.argv[2] + '\''
script += '}'
fs.writeFile(path, script, function (err, file) {
if (err) throw err;
console.log('file saved:', path);
});
Run Code Online (Sandbox Code Playgroud)
从 npm 运行它:
npm run version
> omnitool@0.0.1 version ...
> node gen_version.js $npm_package_version
current version: 0.0.1
file saved: src/environments/version.ts
Run Code Online (Sandbox Code Playgroud)
从您的应用程序使用:
import {Constants} from "../environments/version"
...
console.log('Version:', Constants.version)
Run Code Online (Sandbox Code Playgroud)
Angular 13+ / 离子
这对我有用:
将其放在dev和prod环境文件下。
环境.ts
declare const require: any;
export const environment = {
appVersion: require('../../package.json').version,
};
Run Code Online (Sandbox Code Playgroud)
任何组件的示例用法:
import { environment } from 'src/environments/environment';
constructor() {
console.log(environment.appVersion);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54505 次 |
| 最近记录: |