Your App’s Git Branch In the Title (per env.)

Ben Racicot
2 min readMay 27, 2021

Engineers, are you meticulous about your tooling? I know I am!

The Favicons for Each Environment article led to an Angular (and Webpack) build targets piece… which led to this: how to get the current build’s branch name into your title tag for non-production environments.

This article is part of a series on customizing Webpack build targets.

  1. Configure Angular’s Build System For Local, Dev, Stage and Prod
  2. Favicons for Each Environment
  3. Your App’s Git Branch In the Title (per env.)

This is a 3 step process. First, update your application’s package.json.

If it looks strange visit the Configure Build System article for a walk-through.

{
"name": "aspectratia",
"version": "0.0.0",
"scripts": {
"config": "ts-node ./src/environments/set-env.ts", <-- step one
"ng": "ng",
"start": "npm run config && ng serve --configuration dev",
"start:dev": "npm run config && ng serve --configuration dev",
"start:stage": "npm run config && ng serve --configuration stage",
"start:prod": "npm run config && ng serve --configuration prod",
...
"devDependencies": {
"@types/git-branch": "^2.0.1"

Create the Git branch “set” file anywhere, I chose /environments/set-env.ts

const { writeFile } = require('fs');
const gitBranch = require('git-branch');
gitBranch().then(branchName => {
const content = `
export const customEnv = {
branchName: '${branchName}'
};
`;
writeFile('./src/environments/custom.ts', content, err => {
if (err) {
console.log(err);
} else {
console.log('Updated custom env');
}
});
});

The above uses git-branch to, well… get the Git branch related to this build.

If you take a look at the start commands above they define which environment we’re serving (and building) for.

Again, the Configure Build System article will explain how build targets and configuration flags tell the build system which environment file to use.

Yup, that’s it!

For Angular we have cool utilities for setting SEO related tags.

// seo.service.ts
import { environment } from '@env'; // I use path vars but whatever
...constructor(
private title: Title,
private meta: Meta
) { }
...public setTitle(): void {
this._pageTitle = environment.prod
? `TITLE TEXT`
: `${environment.branchName}`;
this.title.setTitle(this._pageTitle);
}

--

--

Ben Racicot

Hi! I’m passionate about web technology, specifically Angular and all things JavaScript.