如何在AngularCLI中的构建时插入构建号或时间戳

时间:2017-01-19 04:18:10

标签: angular angular-cli

我希望在我的Angular2应用程序的某个地方有一个时间戳或内部版本号,以便我可以判断用户是否使用旧的缓存版本。

如何在AOT编译/构建时使用Angular2中的AngularCLI执行此操作?

11 个答案:

答案 0 :(得分:29)

  1. 安装plugin npm install replace-in-file --save-dev
  2. 添加到prod环境src / environments / environment.prod.ts new 财产

    export const environment = {
      production: true,
      version: '{BUILD_VERSION}'
    }
    
  3. 将构建文件replace.build.js添加到文件夹的根目录

    var replace = require('replace-in-file');
    var buildVersion = process.argv[2];
    const options = {
      files: 'src/environments/environment.prod.ts',
      from: /{BUILD_VERSION}/g,
      to: buildVersion,
      allowEmptyPaths: false,
    };
    
    try {
      let changedFiles = replace.sync(options);
      console.log('Build version set: ' + buildVersion);
    }
    catch (error) {
      console.error('Error occurred:', error);
    }
    
  4. 将脚本添加到package.json

    "updateBuild": "node ./replace.build.js"
    
  5. 在您的应用中使用environment.version

  6. 在构建致电npm run updateBuild -- 1.0.1

  7. 之前

    PS。您必须始终记住{BUILD_VERSION}永远不会被提交。

    PS。我在my blog

    中写了一个更好的解决方案

    PS.3 as @ julien-100000提到你不应该使用更新版本提交environment.prod.ts。版本更新必须仅在构建过程中发生。永远不应该承诺。

答案 1 :(得分:13)

将此步骤添加到您的jenkins-job:

echo export class MyVersion {public static readonly number = '%SVN_REVISION%'} > src\myVersion.ts

您可以访问以下号码:

import {MyVersion} from "../myVersion";

export class AppComponent {
    constructor() {
        console.log("Welcome to MyApp version " + MyVersion.number);
    }
}

此解决方案是 +轻量级 +易于阅读 + robust

答案 2 :(得分:6)

无需安装replace-in-file或执行任何提及的@VolodymyrBilyac步骤。

简单解决方案:使用角度环境

就在您想要的环境中。*。ts文件(有关环境阅读angular-2-and-environment-variables的更多信息),需要package.json,如下所示:

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

然后在您的应用导入环境中:

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

你有environment.version。 如果您收到cannot find name 'require'错误,请阅读this answer

More info

注意:正如评论中提到的@VolodymyrBilyachat,这将在最终的捆绑文件中包含您的package.json文件。

答案 3 :(得分:1)

仅供参考,这里是一个独立于平台的 slartidan's answer 版本。时间戳在构建期间使用 node.js 脚本 (bin/update-timestamp.js) 更新。

bin/update-timestamp.js

#!/usr/bin/env node
'use strict';

const fs = require('fs');
const stamp = new Date().toISOString();
fs.writeFileSync('./src/app/timestamp/Timestamp.ts', `export class Timestamp { public static readonly stamp = '${stamp}'; }`);

package.json

{
  "scripts": {
    "build": "node ./bin/update-timestamp.js && ng build --prod",
  },
}

app.component.ts

import {Timestamp} from './timestamp/Timestamp';

export class AppComponent {

  constructor() {
    console.log("timestamp", Timestamp.stamp);
  }
  
}

答案 4 :(得分:0)

我通过在index.html末尾添加最后一个提交哈希值的注释来解决此问题。例如:

ng build --prod

git rev-parse HEAD | awk '{print "<!-- Last commit hash: "$1" -->"}' >> dist/index.html

然后,您可以在浏览器中执行“查看源代码”,查看HTML底部,然后查看应用程序的已部署版本。

这当然假定您使用git作为版本控制系统。您可以使用输出唯一版本的任何其他命令轻松更改git rev-parse HEAD

答案 5 :(得分:0)

我认为您的情况是:在ng build中添加ng serveenvironment.ts

export class environment {
  production: false,
  buildTimestamp: new Date()
}

然后在您的组件中:

import { environment } from 'src/environments/environment'; // or path to your environment.ts file

...

const buildTimestamp = environment.buildTimestamp;

这就是我想要的。

答案 6 :(得分:0)

讨论可能会有点晚,但是希望我可以帮助其他人解决相同的问题。

我写了一个名为angular-build-info的小npm软件包,其中总结了有关当前构建的一些信息,例如构建时间戳,构建应用的git用户,缩短的提交哈希以及项目package.json文件中的应用版本。

实施该软件包也非常容易,它会在build.ts下创建一个src/build.ts文件,您可以将该文件导入Angular应用并在任何地方显示信息。

实现它的示例如下所示:(app.component.ts

import { Component } from "@angular/core";
import { buildInfo } from "../build";
import { environment } from "../environments/environment";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent {
    constructor() {
        console.log(
            `\n%cBuild Info:\n\n%c ❯ Environment: %c${
                environment.production ? "production ?" : "development ?"
            }\n%c ❯ Build Version: ${buildInfo.version}\n ❯ Build Timestamp: ${
                buildInfo.timestamp
            }\n ❯ Built by: ${buildInfo.user}\n ❯ Commit: ${buildInfo.hash}\n`,
            "font-size: 14px; color: #7c7c7b;",
            "font-size: 12px; color: #7c7c7b",
            environment.production
                ? "font-size: 12px; color: #95c230;"
                : "font-size: 12px; color: #e26565;",
            "font-size: 12px; color: #7c7c7b"
        );
    }
}

将输出: link to console screenshot

我希望这会对某人有所帮助! :)

答案 7 :(得分:0)

如果您不仅要记录/显示版本号,还要记录/显示git的信息(例如哈希,标签等),则可以考虑使用自定义原理图创建我的angular-cli。将其添加到Angular 8+应用程序就像执行一样简单 ng add @w11k/git-info

有关更多文档和见解,请查看https://github.com/w11k/angular-git-info

上可用的文档。

答案 8 :(得分:0)

我查看了其他解决方案,但是我并没有说服使用其他软件包或生成JSON(因为JSON并不完全在应用程序中)。另外,我也不想打扰未提交的更改,例如该线程的已接受答案。

最后,我制作了一个很小的bash脚本,该脚本会自动将位于App中某个位置的字符串替换为从GIT获取的版本+构建的DateTime。

现在,当我构建应用程序时,我只需要执行以下脚本:

latesttag=$(git describe --tags)
now=$(date +'%a %y-%m-%d %H:%M')

sed -i '' "s/build_info/$latesttag/g" ./src/app/pages/home/user-preference/user-preference.component.html
sed -i '' "s/build_time/$now/g" ./src/app/pages/home/user-preference/user-preference.component.html

ng build --prod;

sed -i '' "s/$latesttag/build_info/g" ./src/app/pages/home/user-preference/user-preference.component.html
sed -i '' "s/$now/build_time/g" ./src/app/pages/home/user-preference/user-preference.component.html

在我的文件user-preference.component.html

<footer class="footer mt-auto">
    <div class="container text-center">
        Build: build_info - build_time
    </div>
</footer>

答案 9 :(得分:0)

  1. 创建简单的js文件createBuildDate.js

    例如:

    const { writeFileSync } = require('fs')
    const { join } = require('path')
    
    const TIME_STAMP_PATH = join(__dirname, 'buildDate.json');
    
    const createBuildDate = {
        year: new Date()
    }
    
    writeFileSync(TIME_STAMP_PATH, JSON.stringify(createBuildDate, null, 2));  
    
  2. 在 package.json 中编辑脚本

    "build": "node src/environments/createBuildDate.js && ng build"
    

    或者你可以使用 prebuild

  3. 编辑 tsconfig.json

    "resolveJsonModule": true,
    
  4. 在组件中导入json并使用

答案 10 :(得分:-3)

也许这对某人是一个很好的解决方案。.https://medium.com/@amcdnl/version-stamping-your-app-with-the-angular-cli-d563284bb94d

他描述的是如何使用您的git数据以及如何将最后的提交哈希作为内部版本号。

通过在package.json中添加安装后步骤,运行安装脚本时将生成一个文件。