Automatically Run package.json Scripts upon File Changes in a Folder
In this article, I will show you how to set up a package.json script to re-run automatically whenever a file within a specific folder changes. This approach can be applied to any type of automatic file and folder monitoring, not just limited to the scenario mentioned here.
Let’s start by addressing a practical problem. Suppose you want to automatically regenerate the CSS files, utilizing a PostCSS pipeline, whenever any file changes within a folder.
To illustrate this, I have an existing script called build:css
in my package.json file, which I run using yarn build:css
:
1 | "scripts": { |
Now, I want to trigger the build:css
script whenever any file within the layouts
folder, containing all the HTML files that make up my site, is modified.
If you’re familiar with Tailwind, it generates a CSS file with all the necessary styles. To optimize the CSS output, you can remove any unused classes. Consequently, every time I make changes in the layouts
folder, I want to regenerate the CSS and trigger the configured purge and minification steps within the PostCSS setup.
So, how can we achieve this?
The first step is to install the watch
npm package:
1 | npm install watch |
Next, add the watch
script to your package.json file. Since we already have the build:css
script defined, we’ll simply include a new script that monitors the layouts
folder and executes build:css
on every change:
1 | "scripts": { |
Finally, run npm run watch
or yarn watch
to start monitoring the folder for changes.
By implementing this solution, you can now benefit from the automated re-running of your package.json script whenever a file within the specified folder is modified.
tags: [“technical”, “package.json”, “automation”, “web development”, “CSS”, “PostCSS”]