Use pre and post npm script lifecycle hooks

Elijah Manor
InstructorElijah Manor

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

For each npm script there is a pre and post version of the script that will be called if defined. This can be helpful when you want to enforce a validation check before running a script or inject a specific behavior when a script is executed.

[00:01] NPM Scripts supports the concept of pre and post scripts. Let's create a pretest script that will run before our tests execute. Just by prepending the text pre tells npm to run the script before the test script. We'll move the npm run lint from the test script into the pretest, which cleans up our test script pretty nicely.

[00:24] While we're changing things for tests, let's add test coverage with a task named cover, and have nyc generate a covered report when we run our tests. We'll create a post cover script that will run after the covered script that will clean up all the files that nyc generates when it creating its report.

[00:44] Before running our new scripts, let's add one more to open up a page to our covered report in a browser. We'll say open, coverage, index.html. Now, if we open up our terminal and write our tests, you'll see that first, it runs all the pretests, which are linting, and then it runs the tests.

[01:05] If we say npm, run cover, NYC will gather statistics while the tests are running and generate a summary for us. We could run npm run cover:open to open up the browser and look at our covered report.