Running NPM command on file save

I have the following scripts in my package.json

"scripts": {
    "sass": "node-sass --include-path='./node_modules' --output-style compressed -o dist/css src/scss/compile.scss",
    "autoprefixer": "postcss -u autoprefixer -r dist/css/*",
    "build": "npm run sass && npm run autoprefixer",
  },

How do I run the build script whenever the user saves a SCSS file?

You should use done kind of build tool. Webpack, gulp, parcel, etc. They all have file watchers that will autobuild on save.

I’m trying to keep things simple because it is a small project.
Surely what I want to achieve is possible just with NPM scripts? It seems like a simple thing.
If not, I have used Webpack a tiny bit before so I might try that…
I’m not writing any Javascript for this project so Webpack does feel heavy handed.

It’s not really that simple and it’s not part of node or npm functionality. If you’re doing just sass, then gulp might be the best bet.

But if you don’t want to use a build tool, you could use npm-watch or something similar. I would still opt for gulp.

I think I’ll dodge this entirely for now and just make sure I run the build command before actually committing anything

"scripts": {
    "sass": "node-sass --include-path='./node_modules' --output-style compressed -o dist/css src/scss/compile.scss",
    "autoprefixer": "postcss -u autoprefixer -r dist/css/*",
    "build": "npm run sass && npm run autoprefixer",
    "sass:watch": "npm run sass -- -w"
  },

Or you could do it as a git pre-commit hook?

Watching would be better, but at least you won’t forget it before you commit with the hook.

1 Like

Thanks for the suggestion. I’ve published Javascript to the NPM registry without building beforehand, so I definitely need something like this :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.