DEV Community

Ďēv Šhãh 🥑
Ďēv Šhãh 🥑

Posted on • Edited on

Unlocking the Power of NPM Scripts: Simplify Your Workflow with Pre and Post Keywords

So these days I am working on a couple of Web Development projects where I noticed one thing.
We all know about npm and the script it has which makes our life easy since we don't have to remember the code to run anything due to it. However, I noticed that to run some npm scripts, we use npm run [script name] whereas for others we just use npm [script name] eliminating the keyword 'run'.
Well, this made me curious as to what might be to reason for this difference. Hence, I pulled up the npm script documentation where I some exciting information, I didn't know before.

Pre and Post are the keywords that can be added with the name of the script (it will be a separate script). Using these keywords, you can define some commands that you would like to run before and/or after running some particular script.

For eg, in the following script object of package.json, I have added 'predev' which announces about starting the dev environment. Similarly, I have added 'posttest' which announces about completion of all the tests!

  "scripts": {
    "predev": "echo 'Starting dev environment!'",
    "dev": "nodemon src/server.js",
    "test": "jest -c jest.config.js --runInBand --",
    "posttest": "echo 'Hopefully all of your tests would have passed!'"
  }
Enter fullscreen mode Exit fullscreen mode

These scripts don't need to be run individually; nonetheless, they would be run automatically when the actual script is called. In other words, when the 'dev' script would be called, the 'predev' would run automatically before starting the dev script, and as you might have guessed, once the 'test' script completes its execution, 'posttest' script would start running automatically.

Anyways, with regards to my original query as to why we have to use 'run' for some scripts, well run is mostly used with arbitrary scripts. Arbitrary scripts are scripts that are not predefined in npm. Scripts such as start, test, install, and publish are already predefined in the npm. Hence, in conclusion, the actual way of running any script is npm run [script name]; however, for some predefined scripts, the 'run' keyword can be ignored. Although even if 'run' is included for the predefined script, it would work totally as if it would without 'run'.

If you like my work, you may https://www.buymeacoffee.com/busycaesar7

Top comments (0)