Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Use pre and post npm script lifecycle hooks

    Elijah ManorElijah Manor

    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.

    npmnpm
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss