如何在构建时在 AngularCLI 中插入构建号或时间戳 [英] How to insert a Build Number or Timestamp at build time in AngularCLI

查看:30
本文介绍了如何在构建时在 AngularCLI 中插入构建号或时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

  1. 安装插件 npm install replace-in-file --保存开发
  2. 添加到生产环境 src/environments/environment.prod.ts new属性

    export const environment = {生产:真实,版本:'{BUILD_VERSION}'}

  3. 将构建文件 replace.build.js 添加到文件夹的根目录

    var replace = require('replace-in-file');var buildVersion = process.argv[2];常量选项 = {文件:'src/environments/environment.prod.ts',来自:/{BUILD_VERSION}/g,到:构建版本,allowEmptyPaths: 假,};尝试 {让 changedFiles = replace.sync(options);console.log('构建版本集:' + buildVersion);}捕捉(错误){console.error('发生错误:', error);}

  4. 将脚本添加到 package.json

    "updateBuild": "node ./replace.build.js"

  5. 在您的应用中使用 environment.version

  6. 在构建调用之前 npm run updateBuild -- 1.0.1

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

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

PS.3 正如@julien-100000 提到的,你不应该提交带有更新版本的 environment.prod.ts.版本更新只能在构建过程中发生.并且永远不应该被提交.

I want to have a timestamp or build number somewhere on my Angular2 App so I can tell if a user is using an old cached version or not.

How to do this with AngularCLI in Angular2 at AOT compile/build time?

解决方案

  1. Install plugin npm install replace-in-file --save-dev
  2. Add to prod environment src/environments/environment.prod.ts new property

    export const environment = {
        production: true,
        version: '{BUILD_VERSION}'
    }
    

  3. Add build file replace.build.js to root of your folder

    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. add scripts to package.json

    "updateBuild": "node ./replace.build.js"
    

  5. Use environment.version in your app

  6. Before build call npm run updateBuild -- 1.0.1

PS. You must always remember that {BUILD_VERSION} is never committed.

PS. I wrote a bit better solution in my blog

PS.3 as @julien-100000 mentioned you should not commit environment.prod.ts with updated version. Version update must happen only in build process. And should never be committed.

这篇关于如何在构建时在 AngularCLI 中插入构建号或时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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