如何在Angular应用中显示应用版本?版本应该从包中取出。json文件。

{
  "name": "angular-app",
  "version": "0.0.1",
  ...
}

在Angular 1中。x,我有这个html:

<p><%=version %></p>

在Angular中,它不会被渲染为版本号,而是直接打印出来(<%=version %>而不是0.0.1)。


当前回答

如果你正在使用webpack或angular-cli(使用webpack),你可以只需要package。Json,然后显示那个道具。

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

然后是分量

@Component({
  selector: 'stack-overflow',
  templateUrl: './stack-overflow.component.html'
})
export class StackOverflowComponent {
  public appVersion

  constructor() {
    this.appVersion = appVersion
  }
}

其他回答

将version声明为环境变量是个好主意,这样你就可以在项目的任何地方使用它。(特别是在加载基于版本缓存的文件时,例如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, { flag: '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`);
});

上面的代码段将创建一个新文件/src/environments/version。Ts包含一个名为version的常量,并通过从包中提取的值来设置它。json文件。

为了运行预构建的内容。我们把这个文件添加到包中。Json -> "scripts":{…}”部分。所以我们可以使用下面的代码运行项目:

{
  "name": "YourProject",
  "version": "1.0.0",
  "license": "...",
  "scripts": {
    "ng": "...",
    "start": "node PreBuild.js & ng serve",
  },...
}

现在我们可以简单地导入版本并在任何我们想要的地方使用它:

import { version } from '../../../../environments/version';
...
export class MyComponent{
  ...
  public versionUseCase: string = version;
}

作为已经提出的解决方案的替代方案,我创建了一个简单的JS脚本,将版本写入. TS文件中的一个常量,因此它可以像任何其他TS文件一样读取。

我在任何新版本更改之前调用这个脚本。

代码如下:

// easier with fs-extra, but possible also with node build-in fs
const fs = require('fs-extra');

function storeVersionInTsFile() {
  const packageJson = fs.readJSONSync('./package.json');
  const file = `./src/app/version.ts`;
  const contents = `/**\n * Auto generated file, do not edit.\n */\n\nexport const appVersion = '${packageJson.version}';\n`;
  fs.writeFileSync(file, contents);
}

storeVersionInTsFile()

version.ts的内容:

/**
 * Auto generated file, do not edit.
 */

export const appVersion = '0.3.2';

为了方便起见,我还在package.json中添加了一个脚本:

...
"store-version": "node store-version.js",
"build": "npm run store-version && ng build --configuration production"
...

对于那些不喜欢带包裹的人。查看这个插件ngx-build-plus。


提示:如果你想在不同的文件中使用它,就使用一个注入令牌来提供VERSION,这样就没有更多的declare语句了。

在Angular 12中,从'../../package.json'导入{version};给出一个错误:

. / src /环境/环境。ts:10:13-20 -错误:不应该从默认导出模块导入命名的导出'version'(作为'version'导入)(只有默认导出可用)

继续导入版本,而不会带来包的全部内容的安全隐患。Json到构建中,你可以做:

export const environment = {
  ...
  VERSION: require('../../package.json').version,
};

从https://github.com/angular/angular-cli/issues/3770 # issuecomment - 269822722

如果遇到无法找到名称“要求”错误,请参阅https://stackoverflow.com/a/43129815/418819和https://stackoverflow.com/a/54004979/418819

打印稿

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() {

  }
}

HTML

<div class="row">
    <p class="version">{{'general.version' | translate}}: {{version}}</p>
</div>