Melbourne, Australia
22 January 2017
How to add build version to angular apps when building an app. Firstly I was looking how to solve this problem with angular-cli and did not found anything, then I found stackoverflow question and wrote small script which accept version from build.
But after that I actually start thinking how to improve that solution and I finally come with a bit better solution. First of all i went of from angular and angular-cli to node. In node there is already done versioning
npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease | from-git ]
This is exatly what i was looking for since now my builds can call update patch version and I can use this version in prod versions of my builds.
Now to get it together
npm install replace-in-file --save-dev
export const environment = {
production: true,
version: 'DEV'
};
environment.prod.ts
export const environment = {
production: false,
version: '0.0.0'
};
var replace = require('replace-in-file');
var package = require("./package.json");
var buildVersion = package.version;
const options = {
files: 'src/environments/environment.prod.ts',
from: /version: '(.*)'/g,
to: "version: '"+ buildVersion + "'",
allowEmptyPaths: false,
};
try {
let changedFiles = replace.sync(options);
if (changedFiles == 0) {
throw "Please make sure that file '" + options.files + "' has \"version: ''\"";
}
console.log('Build version set: ' + buildVersion);
}
catch (error) {
console.error('Error occurred:', error);
throw error
}
"build-prod": "npm version patch && node ./replace.build.js && ng build --prod"
Now you can run from command line npm run build-prod it will update version in package.json, then read updated version from package.json and store it in environment.
Now manipulating npm version you can define multiple your version for instance npm version minor will increase your minor and automatically reset patch version.