Angular-cli: How to display app version?

Created on 2 Mar 2017  路  13Comments  路  Source: angular/angular-cli

My package.json has a version number, let's say I want to show that in the footer of my application.

How would I do so?

All I could find is this, but that's not relevant to current angular-cli right? http://stackoverflow.com/questions/34907682/how-to-display-app-version-in-angular2

Most helpful comment

I was also looking into this and went down the same path as @AlecTaylor. I read this thread and then looked into parsing typescript to update a value in a .ts file which I then realized was unnecessary for this task.

This is the solution I came up with

./build/build-pre.js

const path = require('path');
const colors = require('colors/safe');
const fs = require('fs');
const appVersion = require('../package.json').version;

console.log(colors.cyan('\nRunning pre-build tasks'));

const versionFilePath = path.join(__dirname + '/../src/environments/version.ts');

const src = `export const version = '${appVersion}';
`;

// ensure version module pulls value from package.json
fs.writeFile(versionFilePath, src, { flat: 'w' }, function (err) {
    if (err) {
        return console.log(colors.red(err));
    }

    console.log(colors.green(`Updating application version ${colors.yellow(appVersion)}`));
    console.log(`${colors.green('Writing version module to ')}${colors.yellow(versionFilePath)}\n`);
});

And then in my Environment.ts files I import the version from ./version.ts

./src/environments/environment.ts

import { version } from './version';
export const Environment = {
    version: version
}

My npm start script is now "start": "node ./build/build-pre.js && ng s -e qa",

All 13 comments

I'm not on the very latest version but as of beta 30 importing package.json did work. I'd give it a try.

I couldn't import it, and requireing it didn't work with ng build -prod.

Something to consider is that importing or requiring your package.json has the potential to expose development information into your production build.
Two other possible options include:

  • Hard-code the value in the source -- the environment file would probably be the best place
  • Create a _pre-build_ script that injects the version into the source before each build -- the infrastructure to execute this would have to be setup or run manually

I concur with @clydin that the value should be set in your environment files and should be put there via a process outside of the CLI itself. I'm closing this issue as the suggested approach is manual and outside of the CLI.

I was also looking into this and went down the same path as @AlecTaylor. I read this thread and then looked into parsing typescript to update a value in a .ts file which I then realized was unnecessary for this task.

This is the solution I came up with

./build/build-pre.js

const path = require('path');
const colors = require('colors/safe');
const fs = require('fs');
const appVersion = require('../package.json').version;

console.log(colors.cyan('\nRunning pre-build tasks'));

const versionFilePath = path.join(__dirname + '/../src/environments/version.ts');

const src = `export const version = '${appVersion}';
`;

// ensure version module pulls value from package.json
fs.writeFile(versionFilePath, src, { flat: 'w' }, function (err) {
    if (err) {
        return console.log(colors.red(err));
    }

    console.log(colors.green(`Updating application version ${colors.yellow(appVersion)}`));
    console.log(`${colors.green('Writing version module to ')}${colors.yellow(versionFilePath)}\n`);
});

And then in my Environment.ts files I import the version from ./version.ts

./src/environments/environment.ts

import { version } from './version';
export const Environment = {
    version: version
}

My npm start script is now "start": "node ./build/build-pre.js && ng s -e qa",

If you're doing semver, git describe is a cool thing!

// @ts-check
const chalk = require('chalk');
const git = require('git-describe');
const path = require('path');
const fs = require('fs-extra');

const info = git.gitDescribeSync({ longSemver: true });
const file = path.resolve(__dirname, '..', 'src', 'environments', 'version.ts');

fs.writeFileSync(
    file,
    `export const VERSION = ${JSON.stringify(info)};` ,
    { encoding: 'utf-8' });

console.log(chalk.green(`Wrote version info ${info.raw} to ${path.relative(path.resolve(__dirname, '..'), file)}`));
  "scripts: {
    "postinstall": "node scripts/version.js"
  }

I couldn't import it, and requireing it didn't work with ng build -prod.

const { version: appVersion } = require('../../package.json')

this soultion ( from http://stackoverflow.com/questions/34907682/how-to-display-app-version-in-angular2 )
works well for me in Angular 5. Even with ng build --prod
Just make sure to add "node" type inside "types" property in tsconfig.app.ts as mentioned in comments there.

I know this is an older issue, but when trying to solve the same problem i combined the above solution with a line in your packages.json, this makes sure it keeps your version.ts up to date, when using npm version:

"version": "node set-version.js && git add -A .",

Whenever you run npm version x.x.x it will update your version.ts and include it in the commit and tag.

Thanks @thijsvanbuuren for your suggestion. I was able to simplify it a bit with a script to run from the package.json scripts:

_version.sh_

version_file=src/app/app.version.ts
> $version_file
echo "// This file was generated on $(date)
export const appVersion = '$1';" >> $version_file
git add $version_file

_package.json_

...
"version": "0.0.0",
"scripts": {
  "version": "./version.sh $npm_package_version",
  ...

So you can call npm version x.x.x to update the version, which will also trigger the version npm script and regenerate the file. For example:

_app.version.ts_

// This file was generated on Thu Dec 28 20:26:39 CST 2017
export const appVersion = '0.0.0';

Then from a component:

import { appVersion } from 'path/to/app.version';

Notes

The version is passed easily to the script using the $npm_package_<your-variable> syntax. This avoids having to read package.json from a separate script.

npm will automatically generate a commit and tag with the version updated in relevant files. Calling git add from the version script will ensure that the generated file is staged along with the files that npm changes.

See the npm docs

@menehune23 any way you could convert the shell script to a batch file for Windows usage?

@JaxonWright I don't have a Windows machine and haven't run batch scripts in a long time, though the logic is pretty simple: we're just writing some literal text to a file called src/app/app.version.ts. The only variable parts are the date (optional, honestly, but I like to have it), and the first argument.

In Windows, I believe echo works, and the argument can be referenced by %1. Not tested, but should be a good start.

If anyone else with Windows experience wants to chime in, feel free 馃槈.

The shell script works fine as-is for me on Windows 10.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbeckton picture jbeckton  路  3Comments

gotschmarcel picture gotschmarcel  路  3Comments

hareeshav picture hareeshav  路  3Comments

JanStureNielsen picture JanStureNielsen  路  3Comments

NCC1701M picture NCC1701M  路  3Comments