Sunday, 22 January 2017

Angular 2 - Manage application version


Problem

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. 

Solution

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

1. Install npm install replace-in-file --save-dev this plugin will help to replace version file.

2. Insert to environment.ts new property to hold version

environment.ts

export const environment = {
  production: false,
  version: 'DEV'
};


environment.prod.ts

export const environment = {
  production: false,
  version: '0.0.0'
};

3. Insert build script to your project

var replace = require('replace-in-file');
var package = require("./package.json");
var buildVersion = package.version;
const options = {
    files: 'src/environments/environment.prod.ts',
    replace: /version: '(.*)'/g,
    with: "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
}

4. Update package.json and insert new script

"build-prod": "npm version patch && node ./replace.build.js && ng build --prod"

How it works

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.

What else

Now manipulating npm version you can define multiple your version for instance npm version minor will increase your minor and automatically reset patch version.
Volodymyr Bilyachat Web Developer