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

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

问题描述

我想在我的Angular2应用程序的某处有一个时间戳或内部版本号,以便告诉用户是否正在使用旧的缓存版本.

如何在AOT编译/构建时使用Angular2中的AngularCLI做到这一点?

解决方案

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

     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

PS.您必须始终记住,{BUILD_VERSION}从未提交.

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

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天全站免登陆