Skip to content
Advertisement

Executing a JavaScript file when running ng build

I would like to run a JavaScript file in my Angular application every time I run ng build. To be more precise, I want this file to be executed before the build process so that the changes that it makes are present in the build.

Its a simple script that reads the app version and its dependencies and write them to an object.

The file is called pre-build.js and I have tried configuring the build command in package.json as follows, however I can see that the script was not executed:

{
   ...
   ...,
   "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "node pre-build.js && ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
   },
   ...,
   ...,
}

The path of the script is ./pre-build.js. I assume that I have to change more configurations in order to achieve this but I am not able to find out where. Any leads will be appreciated.

Edit:

This is the content of pre-build.js:

const path = require('path');
const fs = require('fs');
const appVersion = require('./package.json').version;
const appDeps = JSON.stringify(require('./package.json').dependencies);

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

const src = `export const version = '${appVersion}';nexport const buildTime = '${new Date()}';nexport const deps = ${appDeps};`;

// ensure version module pulls value from package.json
fs.writeFile(versionFilePath, src, (err) => {
  if (err) {
    console.log(err);
  }
});

When I run node pre-build.js in the terminal, the code works fine and updates the version.ts file. But i want to somehow automatically execute this command every time i run ng build. Which so far i was not able to do so.

Advertisement

Answer

Edit

The correct answer to this problem is that you shouldn’t run ng build but should run npm run build since you want to execute the script. When you do ng build this would only trigger the build for angular and wouldn’t update your version file indeed.

Below is an example of your exact same code when doing npm run build, so make sure to update how you build.

enter image description here

Give it a try and let me know if this is still an issue.


Old answer

You can create a “.sh” script to other execute everything you need. This might be helpful later on to add more pre or post build commands

Here is an example

package.json

"scripts": {
  "build:angular": "ng build",
  "build": ./build.sh
}

build.sh

#!/bin/bash
node ./pre-build.js

npm run build:angular

Make sure that pre-build is executable so is the build.sh (chmod https://askubuntu.com/questions/229589/how-to-make-a-file-e-g-a-sh-script-executable-so-it-can-be-run-from-a-termi )

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement