Use pre and post npm script lifecycle hooks

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 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.

egghead
egghead
~ 44 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today