npm: Run package.json scripts upon any file changes in a folder

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


My practical problem: I want to automatically regenerate the CSS, going through a PostCSS pipeline, upon file changes.

The approach I describe will work for any kind of automatic file and folder watching, not just for this specific case.

I have this script in action, which I run using yarn build:css:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css",
}

and I want to re-run it whenever something changes in the layouts folder, which contains all the HTML files that build up my site.

If you’re familiar with Tailwind, it creates a slightly big CSS files with all the things you might need, and you can optimize it by removing any class you don’t use.

Every time I change something in there, I want to regenerate the CSS, and trigger the purge and minification I set up in the PostCSS setup.

How to do this?

Install the watch npm package:

npm install watch

and add the watch script to your package.json file. You already had build:css from before, we just add a script that watches the layouts folder and runs build:css upon every change:

"scripts": {
  "build:css": "postcss src/tailwind.css -o static/dist/tailwind.css",
  "watch": "watch 'npm run build:css' ./layouts"
}

Now run npm run watch or yarn watch.

Lessons in this unit:

0: Introduction
1: How to use or execute a package installed using npm
2: npm dependencies and devDependencies
3: How to fix the "Missing write access" error when using npm
4: npm can install packages in the parent folder
5: Install an older version of an npm package
6: Find the installed version of an npm package
7: How to test an npm package locally
8: npm global or local packages
9: What are peer dependencies in a Node module?
10: `npm run dev` is a long-running program
11: Semantic Versioning using npm
12: Uninstalling npm packages with `npm uninstall`
13: An introduction to the npm package manager
14: The npx Node Package Runner
15: The package.json guide
16: The package-lock.json file
17: What is pnpm?
18: Should you commit the node_modules folder to Git?
19: Update all the Node dependencies to their latest version
20: Where does npm install the packages?
21: Bumping Node.js dependencies
22: ▶︎ Run package.json scripts upon any file changes in a folder