samedi 5 mai 2012

How to Write a CSS Preprocessor Using Node.js?

CSS preprocessors seem to be really popular these days. At least there are many to choose from. See Stylus, Sass and LESS for example. These kind of tools provide some functionality missing from vanilla CSS and make it more fun to write. Some popular features include variables, functions, mixins, nesting and overall lighter syntax.

Node.js (or just Node) is another emerging technology. It is currently the leading server-side solution available for JavaScript. Effectively it enables us to use JavaScript in the whole stack instead of just client side. Some claim this makes it easier to develop (no linguistic context switch). Anyhow it's one the hot technologies out there at the moment.

In this post I'm going to show you how to use Node to write a CSS preprocessor with a selected few features. Since "less is more" I'm simply going to call this little project as "more.js". Hopefully this post gives you some ideas on how you might write your own preprocessor.

In principle they're very simple. You just take some data in, transform it and finally spit it out. Most of the magic happens in that transformation stage. I'll start with the ends (read file, write file) and move onto actual business logic right after that.

I'll be using Node v0.6.6 since that's what I've installed on my Mac at the moment. If you are a Mac person too, you can easily install it via MacPorts simply by invoking "sudo port install nodejs" at terminal. If you are using Linux you should be able to find Node from your local package management system. Note that it might not be the freshest version available so you're probably better off installing it by other means. You could just grab a package directly from their site and install that. There's a Windows version available too.

The code will likely work with a lot older version of Node as well. I used only a couple of Node specific features (mainly file IO). The rest is just vanilla JavaScript.

Read more »

Aucun commentaire:

Enregistrer un commentaire