Node.js: Theming your Express application

The Express team has done a decent job of making sure Express applications look okay out of the gate. Our Notes application won’t win any design awards, but at least it isn’t ugly. There’s a lot of ways to improve it, now that the basic application is running. Let’s take a quick look at theming an Express application. In Chapter 6, Implementing the Mobile-First Paradigm, we’ll take a deeper dive into this, focusing on that all-important goal of addressing the mobile market.

If you’re running the Notes application using the recommended method, npm start, a nice log of activity is being printed in your console window. One of these is the following:

GET /stylesheets/style.css 304 0.702 ms – –

This is due to the following line of code, which we put into layout.hbs:

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

This file was autogenerated for us by the Express generator at the outset and was dropped in the public directory. The public directory is managed by the Express static file server, using the following line in app.mjs:

app.use(express.static(path.join( dirname, ‘public’)));

Therefore, the CSS stylesheet is at public/stylesheets/style.css, so let’s open it and take a look:

body {

padding: 50px;

font: 14px “Lucida Grande”, Helvetica, Arial, sans-serif;

}

a {

color: #00B7FF;

}

Something that leaps out is that the application content has a lot of whitespace at the top and left-hand sides of the screen. The reason for this is that the body tags have the padding: 50px style. Changing it is a quick business.

Since there is no caching in the Express static file server, we can simply edit the CSS file and reload the page, and the CSS will be reloaded as well.

Let’s make a couple of tweaks:

body {

padding: 5px;

..

}

..

header {

background: #eeeeee;

padding: 5px;

}

This changes the padding and also adds a gray box around the header area. As a result, we’ll have the following:

We’re not going to win any design awards with this either, but there’s the beginning of some branding and theming possibilities. More importantly, it proves that we can make edits to the theming.

Generally speaking, through the way that we’ve structured the page templates, applying a site-wide theme is just a matter of adding appropriate code to layout.hbs, along with appropriate stylesheets and other assets.

In Chapter 6, Implementing the Mobile-First Paradigm, we will look at a simple method to add these frontend libraries to your application.

Before closing out this chapter, we want to think ahead to scaling the application to handle multiple users.

Source: Herron David (2020), Node.js Web Development: Server-side web development made easy with Node 14 using practical examples, Packt Publishing.

Leave a Reply

Your email address will not be published. Required fields are marked *