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

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

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

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

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


当前回答

角13+ /离子型

这对我来说很管用:

把它放在dev和prod环境文件下。

environment.ts

declare const require: any;

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

任何组件的示例用法:

import { environment } from 'src/environments/environment';

     constructor() {
        console.log(environment.appVersion);
      }

其他回答

尝试DyslexicDcuk的答案,结果是找不到name require

然后,阅读https://www.typescriptlang.org/docs/handbook/modules.html中的“可选模块加载和其他高级加载场景”部分帮助我解决了这个问题。(Gary在这里提到了https://stackoverflow.com/a/41767479/7047595)

使用下面的声明来要求package.json。

declare function require(moduleName: string): any;

const {version : appVersion} = require('path-to-package.json');

角13+ /离子型

这对我来说很管用:

把它放在dev和prod环境文件下。

environment.ts

declare const require: any;

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

任何组件的示例用法:

import { environment } from 'src/environments/environment';

     constructor() {
        console.log(environment.appVersion);
      }

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


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

打印稿

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>

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

我使用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文件。以下是我从现有应用中截取的几张截图。