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

Rod*_*ney 37 angular-cli angular

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

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

Vol*_*hat 37

  1. 安装插件 npm install replace-in-file --save-dev --save-dev
  2. 添加到prod环境src/environments/environment.prod.ts新属性

    export const environment = {
      production: true,
      version: '{BUILD_VERSION}'
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将脚本添加到package.json

    "updateBuild": "node ./replace.build.js"
    
    Run Code Online (Sandbox Code Playgroud)
  5. environment.version在您的应用中使用

  6. 在构建呼叫之前 npm run updateBuild -- 1.0.1

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

PS.我在博客中写了一个更好的解决方案

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


sla*_*dan 15

将此步骤添加到jenkins-job:

echo export class MyVersion {public static readonly number = '%SVN_REVISION%'} > src\my-version.ts
Run Code Online (Sandbox Code Playgroud)

你可以访问这样的数字:

import {MyVersion} from "../my-version";

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

该解决方案是+ lightweight,+ easy to read,+ robust.


Vah*_*hid 9

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

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

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

export const environment = {
    version: require('../package.json').version
};
Run Code Online (Sandbox Code Playgroud)

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

import { environment } from '../environments/environment';
Run Code Online (Sandbox Code Playgroud)

而且你有environment.version。如果遇到cannot find name 'require'错误,请阅读此答案

更多信息

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

  • 我之所以询问require如何与摇树一起工作的原因是,基本上,它是将所有内容注入捆绑中。因此,如果确实需要package.json,则应该了解该文件的全部内容都将捆绑到您的min脚本中。如果您对此表示满意,那就很好。是的,您的链接与我的问题完全无关 (4认同)
  • @VolodymyrBilyachat有用的信息!谢谢 (2认同)

kli*_*mir 8

  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));  
    
    Run Code Online (Sandbox Code Playgroud)
  2. 编辑 package.json 中的脚本

    "build": "node src/environments/createBuildDate.js && ng build"
    
    Run Code Online (Sandbox Code Playgroud)

    或者你可以使用prebuild

  3. 编辑 tsconfig.json

    "resolveJsonModule": true,
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在组件中导入json并使用


ted*_*edw 6

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

ng build --prod

git rev-parse HEAD | awk '{print "<!-- Last commit hash: "$1" -->"}' >> dist/index.html
Run Code Online (Sandbox Code Playgroud)

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

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


小智 6

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

我编写了一个名为 npm 的小包angular-build-info,它总结了有关当前构建的一些信息,例如构建时间戳、构建应用程序的 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"
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

这将输出: 链接到控制台屏幕截图

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

  • 不错的包,但我不想为这个简单的功能添加另一个依赖项到我的项目中。 (2认同)

Pie*_*rre 6

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

我最终制作了一个小型 bash 脚本,该脚本自动将位于我的应用程序中某处的字符串替换为从 GIT + 构建的日期时间获得的版本。

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

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
Run Code Online (Sandbox Code Playgroud)

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

<footer class="footer mt-auto">
    <div class="container text-center">
        Build: build_info - build_time
    </div>
</footer>
Run Code Online (Sandbox Code Playgroud)