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

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

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

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

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


当前回答

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

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

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

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

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

:完成)

其他回答

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

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

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

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

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

export const environment = {
  version: npm.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"
...

你可以看包装。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);
    }
}

使用tsconfig选项——resolveJsonModule你可以在Typescript中导入json文件。

在环境方面。ts文件:

import { version } from '../../package.json';

export const environment = {
    VERSION: version,
};

现在可以使用environment了。应用程序中的版本。