Feb 25, 2016

Replacing HTML with Jade in Express applications

Jade is great. You can progress faster and that of course is valuable. So, here is how you can make your Express application one that utilizes the strengths of Jade.

Add Jade to your project.

npm install --save jade

First of all, get Express to know that you actually want to use Jade now. Therefor go to the Express configuration file of your project. It’s most of the times located in the root directory of your project and named either app.js or server.js. Just add these lines:

var path = require('path');
app.set('views', path.join(__dirname, '/views')); // dir of where your view files are
app.set('view engine', 'jade');

Your routing changes. You should now render stuff.

app.get('*', function(req, res) {

You see, it’s just index. This is it. You’ve told Express that your view files are in /views and from there on it will look for the file. You’ve also told it that files should be Jade files, so it expects index to be an index.jade file. A sophisticated approach of course should include checks for errors during rendering. Please refer to the Express API. Also adjust your routing according to what routes you need.

Also your HTML files should now become Jade files and contain Jade code rather than HTML markup. Here’s an example.

<div class="jumbotron text-center">
    <h1>Geek City</h1>
    <p>I’m all nerdy</p>


  h1 Geek City
  p I’m all nerdy

You can take advantage of the HTML 2 Jade Converter.

You’re basically doing nothing more than just telling Express that you want to use Jade, where those Jade files are and that you want to render them.

Please mind the trap when using AngularJS and HTML5 mode URLs. Refer to this page for more information on that.

Here’s a demo of me replacing HTML with Jade.