Join egghead, unlock knowledge.

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
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Run npm scripts when files change with onchange

    Elijah ManorElijah Manor

    In this lesson we will look at how we can setup our npm scripts to execute when the file system has changed. Some common examples of this are automatically linting your code, running unit tests, or using a pre-processor for your CSS.



    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




    Instructor: Some command line programs already support the watch flag, much like Mocha here -- we're passing the watch flag to our tests -- but not all of them do. For example, if we wanted to add a watch script for linting, we might name this to watch:lint, and then come over here, and say npm run lint. Then pass the watch flag.

    Well, ESLint doesn't support a watch flag, so we're out of luck. Thankfully, however, there's a handy program called on-change that we could use just for that. Let's install that package on the terminal with npm -i on-change, and -d for dev dependency.

    We'll go back to our script, and instead of what we have here, we'll use on-change to watch all of our JavaScript files and our Sass files. Then we'll tell on-change the script we want to run if any of these files change.

    Don't worry, by default, on-change ignores the Node modules folder. Let's save our script and go back to the terminal. Now, we can run npm run watch:lint, which will kick up a watch to lint all of our files. Now, if we open up one of our source files, like utils, for example, and save it, our watch sees that the file has changed and runs our linting.

    Let's cancel this, and go back to our scripts again. This time, let's add a generic script to watch all of our files. We'll use npm run all, and in parallel mode, we'll watch all of our subscripts. We'll say :*, which will run watch:test and watch:lint.

    If I save that and come back to the terminal, and run npm run watch, it'll kick up two watches, both for our code, our styles, and our tests. If I open a unit test file, for example, and save that, it'll rerun our tests and lint it.

    If I open up one of our Sass files, make a save in there, it'll also lint that. That's the on-change package.