Programming

Angular에서 앱 버전을 표시하는 방법은 무엇입니까?

procodes 2020. 8. 22. 12:30
반응형

Angular에서 앱 버전을 표시하는 방법은 무엇입니까?


Angular 애플리케이션에서 앱 버전을 어떻게 표시합니까? 버전은 package.json파일 에서 가져와야합니다.

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

각도 1.x에는 다음과 같은 html이 있습니다.

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

각도에서 이것은 버전 번호로 렌더링되지 않고 대신 그대로 인쇄됩니다 ( <%=version %>대신 0.0.1).


Angular 앱에서 버전 번호를 사용 / 표시하려면 다음을 수행하십시오.

전제 조건 :

  • Angular CLI를 통해 생성 된 Angular 파일 및 폴더 구조

  • TypeScript 2.9 이상! (Angular 6.1 이상에서 지원)

단계 :

  1. 당신의에서 것은 /tsconfig.app.jsonresolveJsonModule 옵션을 (서버 다시 시작 이후 필수) 수 :
    "compilerOptions": {
      ...
      "resolveJsonModule": true
      ...
  1. 그런 다음 구성 요소에서 예를 들어 /src/app/app.component.ts버전 정보 사용하십시오.
    import { version } from '../../package.json';
    ...
    export class AppComponent {
      public version: string = version;
    }

또한 environment.ts 파일에서 2 단계를 수행하여 거기에서 버전 정보에 액세스 할 수 있습니다.

Thx @Ionaru@MarcoRinck .

이 솔루션에는 package.json 내용이 포함되지 않고 버전 번호 만 포함됩니다.
Angular8 / Node10 / TypeScript3.4.3으로 테스트되었습니다.

package.json의 내용에 따라이 솔루션을 사용하도록 앱을 업데이트하십시오. 원래 솔루션은 보안 문제를 포함 할 수 있습니다.


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
  }
}

DyslexicDcuk의 답변을 시도하면 cannot find 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');

tsconfig 옵션 --resolveJsonModule사용하여 Typescript에서 json 파일을 가져올 수 있습니다.

environment.ts 파일에서 :

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

export const environment = {
    VERSION: version,
};

이제 environment.VERSION응용 프로그램에서 사용할 수 있습니다 .


version환경 변수 로 선언하는 것이 좋습니다. 따라서 프로젝트의 모든 곳에서 사용할 수 있습니다. (특히 버전에 따라 캐시 할 파일을로드하는 경우 e.g. 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, { flat: '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에서 추출한 값으로 설정 package.json합니다.

PreBuild.jsonon build의 콘텐츠를 실행하기 위해 다음과 같이 Package.json-> "scripts": { ... }"섹션 에이 파일을 추가합니다 . 따라서 다음 코드를 사용하여 프로젝트를 실행할 수 있습니다 npm start.

{
  "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;
}

"Angle Bracket Percent"가 angular1과 관련이 없다고 생각합니다. 이전 프로젝트에서 사용되고 있다는 사실을 알지 못하는 다른 API에 대한 인터페이스 일 수 있습니다.

가장 쉬운 해결책 은 HTML 파일에 수동으로 버전 번호를 나열하거나 여러 위치에서 사용하는 경우 전역 변수에 저장하는 것입니다.

<script>
  var myAppVersionNumber = "0.0.1";
</script>
...
<body>
  <p>My App's Version is: {{myAppVersionNumber}}</p>
</body>

더 어려운 솔루션 : package.json 파일에서 버전 번호를 추출하는 빌드 자동화 단계를 실행 한 다음 index.html 파일 (또는 js / ts 파일)을 다시 작성하여 값을 포함합니다.

  • 지원하는 환경에서 작업하는 경우 package.json 파일을 가져 오거나 요구할 수 있습니다.

    var version = require("../package.json").version;

  • This could also be done in a bash script that reads the package.json and then edits another file.

  • You could add an NPM script or modify your start script to make use of additional modules to read and write files.
  • You could add grunt or gulp to your pipeline and then make use of additional modules to read or write files.

Typescript

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>

Simplist solution for angular cli users.

Add declare module '*.json'; on src/typings.d.ts

And then on src/environments/environment.ts:

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

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

Done :)


I have tried to solve this in a bit different way, also considering the ease of convenience and maintainability.

I have used the bash script to change the version across the whole application. The following script will ask you for the desired version number, and the same is applied throughout the application.

#!/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;

I have saved this script in a file named version-manager.sh in the root of the project, and in my package.json file, I also created a script to run it when it is necessary to modify the version.

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

Finally, I can just change the version by executing

npm run change-version 

This command will change the version in the index.html template and also in the package.json file. Following were the few screenshots taken from my existing app.

enter image description here

enter image description here

enter image description here

enter image description here


You could read package.json just like any other file, with http.get like so:

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);
    }
}

참고URL : https://stackoverflow.com/questions/34907682/how-to-display-the-app-version-in-angular

반응형