如何在Angular中显示应用程序版本? [英] How to display the app version in Angular?

查看:97
本文介绍了如何在Angular中显示应用程序版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在角度应用程序中显示应用程序版本?版本应取自package.json文件

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

在angular 1.x中,我有这个html:

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

以角形显示时,它不会显示为版本号,而是按原样打印(<%=version %>而不是0.0.1).

解决方案

如果要在角度应用中使用/显示版本号,请执行以下操作:

先决条件:

  • 通过Angular CLI创建的Angular文件和文件夹结构

  • TypeScript 2.9或更高版本! (从Angular 6.1起受支持)

步骤:

  1. 在您的/tsconfig.json中(有时在/src/tsconfig.app.json中也是必要的)启用resolveJsonModule选项(此后需要重新启动Webpack开发服务器):

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

  1. 然后在您的组件中,例如/src/app/app.component.ts使用版本信息:

    import { version } from '../../package.json';
    ...
    export class AppComponent {
      public version: string = version;
    }

还可以在您的environment.ts文件中执行第2步,从而可以从那里访问版本信息.

感谢 @Ionaru @MarcoRinck .

此解决方案将不包括package.json内容,仅包括版本号.
在Angular8/Node10/TypeScript3.4.3.中进行了测试

请更新您的应用以使用此解决方案,原因取决于您的package.json的内容,原始解决方案可能会涉及安全问题.

How do I display the app version in angular application? the version should be taken from package.json file

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

In angular 1.x, I have this html:

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

In angular, this is not rendered as version number, but instead just printed as it is (<%=version %> instead of 0.0.1).

解决方案

If you want to use/show the version number in your angular app please do the following:

Prerequisites:

  • Angular file and folder structure created via Angular CLI

  • TypeScript 2.9 or later! (Supported from Angular 6.1 upwards)

Steps:

  1. In your /tsconfig.json (sometimes also necessary in /src/tsconfig.app.json) enable the resolveJsonModule option (webpack dev server restart required afterwards):

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

  1. Then in your component, for example /src/app/app.component.ts use the version info:

    import { version } from '../../package.json';
    ...
    export class AppComponent {
      public version: string = version;
    }

It's also possible to do step 2 in your environment.ts file, making the version info accessible from there.

Thx @Ionaru and @MarcoRinck for helping out.

This solution will not include the package.json contents, only the version number.
Tested w/Angular8/Node10/TypeScript3.4.3.

Please update your apps to use this solution cause depending on the contents of your package.json the original solution may implicate security issues.

这篇关于如何在Angular中显示应用程序版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆