Stylus, LESS and SASS - Express.js Guide: The Comprehensive Book on Express.js (2014)

Express.js Guide: The Comprehensive Book on Express.js (2014)

Stylus, LESS and SASS

CSS is tedious to write and manage in complex projects. Stylus, LESS and SASS bring so much needed sanity of reusability (mixins, extend, vars, etc.) to stylesheets.

29.1 Stylus

Stylus is a sibling of Express.js and the most-often used CSS framework. To install Stylus, type and run $ npm install stylus --save. Then, to apply static middleware, include this in your server file:

1 ...

2 app.use(require('stylus').middleware(__dirname + '/public'));

3 app.use(express.static(path.join(__dirname, 'public')));

4 ...

Put *.styl file(s) inside of the folder that we expose (e.g., public/css) and include them in Jade templates with *.css extension:

1 ...

2 head

3 link(rel='stylesheet', href='/stylesheets/style.css')

4 ...

Or, in any other templates of your choice, or in plain HTML file(s):

1 <link rel="stylesheet" href="/stylesheets/style.css"/>

For a project created from scratch, someone can use the $ express -c stylus express-app command.

You’ll find the stylus-enabled project in the expressjsguide/stylus folder as well as on GitHub.

29.2 LESS

To use LESS with Express.js v3.x, we’ll need less-middleware which is an external NPM module:

1 $ npm install less-middleware --save

Then, we need to add less-middleware before the static and router ones:

1 ...

2 app.use(require('less-middleware')({

3 src: __dirname + '/public',

4 compress: true

5 }));

6 app.use(express.static(path.join(__dirname, 'public')));

7

8 app.use(app.router);

9 ...

10 //your routes

Assuming the LESS file(s) are in public/css, we can link the *.css file(s) and the rest will be handled automatically, e.g., a Jade template might use this:

1 ...

2 head

3 link(rel='stylesheet', href='/stylesheets/style.css')

4 ...

Or, in any other template of your choice, or in plain HTML file(s):

1 <link rel="stylesheet" href="/stylesheets/style.css"/>

For a project created from scratch, someone can use the $ express -c less express-app command.

You’ll find the less-enabled project in the expressjsguide/less folder as well as on GitHub.

29.3 SASS

To use SASS with Express.js v 3.x, we need node-sass(GitHub) which is an external NPM module:

1 $ npm install node-sass --save

This is our Express.js plug-in for SASS:

1 ...

2 app.use(app.router);

3 app.use(require('node-sass').middleware({

4 src: __dirname + '/public',

5 dest: __dirname + '/public',

6 debug: true,

7 outputStyle: 'compressed'

8 }));

9 app.use(express.static(path.join(__dirname, 'public')));

10 ...

The Jade template also imports the *.css file:

1 link(rel='stylesheet', href='/stylesheets/style.css')

The sass-enabled project is in the expressjsguide/sass folder, as well as on GitHub.