Skip to content

Instantly share code, notes, and snippets.

@himynameisdave
Last active November 9, 2015 19:40
Show Gist options
  • Save himynameisdave/bf51fe0e15e1930e2ae2 to your computer and use it in GitHub Desktop.
Save himynameisdave/bf51fe0e15e1930e2ae2 to your computer and use it in GitHub Desktop.
Dead Simple Watch+Compile a Less File

Dead Simple Watch+Compile a Less File

Simply watches a Less file and compiles it on save.

Wat/Why?

Sometimes installing something like Gulp or Grunt is annoying if all you want to do is have a simple watch+compile going on. This includes PostCSS for the sake of Autoprefixer but you can obviously also add other PostCSS plugins to this script with ease.

Install Deps

Install Less, PostCSS & AutoPrefixer as a baseline.

npm i less postcss autoprefixer

You can also install other PostCSS plugins you'd like to use. There's lots. Look, I even keep a list 👀.

Update your Node version

I wrote this/tested this on node v4.2.1 so make sure you have at least that version of node installed. It may work on some earlier versions as well, but it's ES6exual so it will probably break on any pre-4.0.0 version. Check your version by running node -v.

Pro Tip: Use nvm to quickly jump between node versions.

Run the script

Run node watch.js your-input-less-file.less your-output-css-file.css to start waching your file. If no arguments are supplied, it will attempt to watch styles.less. If only one argument is supplied, it will output to styles.css.

"use strict";
const fs = require('fs'),
less = require('less'),
plugins = [
require('autoprefixer')({ browsers: ["last 4 versions", "> 1%", "ios 5", "ie 9", "android 4.1"] })
// Require other plugins here
],
postcss = require('postcss'),
files = {
in: process.argv[2] || './styles.less',
out: process.argv[3] || './styles.css'
// If no argument(s) is/are supplied, we use 'styles.{css, less}' as the files
};
// Begin watching our file
fs.watchFile( files.in, ( curr, prev ) => {
// Render from less->css
less.render( fs.readFileSync( files.in, 'utf8' ), (e, out) => {
if(e) return console.warn(e);// Log any errors
// Apply PostCSS transforms
postcss( plugins )
.process( out.css, { from: files.in, to: files.out } )
.then( res => {
// Write the clean CSS to the new file
fs.writeFileSync( files.out, res.css );
console.log("Updated the main.css file!");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment