如何在AngularCLI中的构建时插入内部版本号或时间戳 [英] How to insert a Build Number or Timestamp at build time in AngularCLI
问题描述
我想在我的Angular2应用程序的某处有一个时间戳或内部版本号,以便告诉用户是否正在使用旧的缓存版本.
如何在AOT编译/构建时使用Angular2中的AngularCLI做到这一点?
- 安装插件
npm install replace-in-file --save-dev
-
添加到产品环境src/environments/environment.prod.ts新 财产
export const environment = { production: true, version: '{BUILD_VERSION}' }
-
将构建文件
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); }
-
将脚本添加到package.json
"updateBuild": "node ./replace.build.js"
-
在应用中使用
environment.version
-
构建调用之前
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?
- Install plugin
npm install replace-in-file --save-dev
Add to prod environment src/environments/environment.prod.ts new property
export const environment = { production: true, version: '{BUILD_VERSION}' }
Add build file
replace.build.js
to root of your foldervar 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); }
add scripts to package.json
"updateBuild": "node ./replace.build.js"
Use
environment.version
in your appBefore 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屋!