Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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.

    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

    Instructor: 00:02 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.

    00:22 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.

    00:38 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.

    00:55 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.

    01:18 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.

    01:40 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.

    01:57 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.

    Discuss

    Discuss