Sling Academy
Home/Node.js/NodeJS: Link to static assets (JS, CSS) in Pug templates

NodeJS: Link to static assets (JS, CSS) in Pug templates

Last updated: February 06, 2024

Overview

When building web applications with Node.js and Pug template engine, handling static assets like JavaScript, CSS files, images, and fonts is crucial for rendering web pages. This tutorial provides a comprehensive guide on how to effectively link to static assets in Pug templates within a Node.js environment. Understanding this linkage is key to developing interactive, well-designed web applications.

Setting up Your Project

Before diving into the specifics of linking static assets in Pug templates, ensure your environment is set up correctly. You will need Node.js installed on your machine. The following steps help you to set up a new Node.js project.

mkdir myProject
cd myProject
npm init -y
npm install express pug

Create a directory structure similar to:

myProject/
├── public/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── script.js
├── views/
│   ├── index.pug
└── app.js

This structure includes public for storing your static assets and views for your Pug templates.

Serving Static Assets

To make your static assets accessible to your Pug templates, you must first tell Express (the framework you’re likely using with Node.js) to serve these files. This is done using the express.static middleware.

const express = require('express');
const app = express();

app.use(express.static('public'));

After adding the above code to your app.js, Express now serves the files in the public directory under the root URL path.

Linking Static Assets in Pug Templates

With the setup complete, it’s time to link these assets in your Pug templates. When you reference static files in Pug, you don’t need to specify the public directory in the path—the path starts directly within public.

Linking CSS Files

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

To include a CSS file in your Pug template, use the link tag with the rel attribute set to stylesheet, and the href attribute providing the path to your CSS file as shown above.

Linking JavaScript Files

script(src='/js/script.js')

JavaScript files can be linked similarly by using the script tag with the src attribute pointing to the file within the public directory.

Working with Subdirectories

It’s common to organize assets into subdirectories. It’s important to note that the path you use in Pug should mirror the directory structure within public.

Example:

// Assuming an asset structure with deeper subdirectories
img(src='/images/photos/profile.jpg')

In this case, you link an image residing in /public/images/photos/ by specifying its path relative to the public directory in your Pug file.

Best Practices

When linking to static assets in your Pug templates, there are several best practices to consider:

  • Versioning: Manage cache and force browser to download updated files by appending a version query string to asset URLs e.g., ?v=1.2.
  • Minification: Use tools to minify CSS and JS files, reducing load times and improving performance.
  • Optimization: Optimize images and other assets for the web. Smaller file sizes improve load times significantly.

Conclusion

Effectively managing and linking static assets in your Pug templates enhances your web application’s responsiveness, design, and performance. This tutorial outlined the essential steps to set up your Node.js project correctly, serve static assets using Express, and link them in your Pug templates. With these foundations, you’re well-equipped to create dynamic, efficient, and attractive Node.js applications.

Remember, every web application is unique, and as your project grows, always be prepared to adapt and optimize your approach to handling static assets.

Next Article: NodeJS: Displaying images and links in Pug templates

Previous Article: Node + Express: How to add Paypal payment

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates
  • ExpressJS: How to pass variables to Pug templates