Nick James

NPM pre- and post- hooks

Recently I've been doing a lot of JavaScript/Typescript development. I use npm scripts to handle a few longer commands for me, like run test or start nodemon. The basic format of such a script inside your package.json file looks like the following:  


{
  "scripts": {
    "basic_script": "echo I'm a script"
  }
}

You can run the script using the following command

 

  npm run basic_script

Pre and Post Hooks

Pre and post hooks for npm scripts are great if you want to execute a command before or after another command. It's as simple as creating a new script entry and prepending the word pre or post on the script name.


{
  "scripts": {
    "prebasic_script": "echo Prescript hook",
    "basic_script": "echo I'm a script",
    "postbasic_script": "echo Postscript hook"
  }
}

Now if you run the script again like so:

 

  npm run basic_script

You will see all three statements executed.

Reference material

https://stackoverflow.com/questions/40471152/tell-typescript-to-compile-json-files

Author image
About Nick James