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

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

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

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

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


当前回答

这个答案只针对Angular 12+。它使用Webpack 5。

根据webpack5文档

新规范不支持这一点,您将得到一个警告。而不是:

import { version } from './package.json';
console.log(version);

use:

import pkg from './package.json';
console.log(pkg.version);

另外,你必须在tsconfig.json中提供

"compilerOptions": {
  ...
  "allowSyntheticDefaultImports": true
  "resolveJsonModule":true
  ...

其他回答

如果你正在使用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;
}

我尝试用一种不同的方式来解决这个问题,同时考虑到便利性和可维护性。

我使用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;

我将这个脚本保存在项目根目录下一个名为version-manager.sh的文件中,并保存在我的包中。json文件,我还创建了一个脚本,当需要修改版本时运行它。

"change-version": "bash ./version-manager.sh"

最后,我可以通过执行来更改版本

npm run change-version 

这个命令将改变index.html模板和包中的版本。json文件。以下是我从现有应用中截取的几张截图。

你可以看包装。Json就像任何其他文件一样,带有http。像这样:

import {Component, OnInit} from 'angular2/core';
import {Http} from 'angular2/http';

@Component({
    selector: 'version-selector',
    template: '<div>Version: {{version}}</div>'
})

export class VersionComponent implements OnInit {

    private version: string;

    constructor(private http: Http) { }

    ngOnInit() {
        this.http.get('./package.json')
            .map(res => res.json())
            .subscribe(data => this.version = data.version);
    }
}

为angular cli用户提供简单的解决方案。

添加声明模块'*.json';在src / typings.d.ts

然后在src/environments/environment.ts上:

import * as npm from '../../package.json';

export const environment = {
  version: npm.version
};

:完成)