Open In App

How to include css files using NodeJS, Express, and EJS?

CSS stands for “Cascading Style Sheet”. It is used to style web pages. CSS simplifies the process of making web pages presentable. It describes how web pages should look it prescribes colors, fonts, spacing, and much more. Including CSS files is important for styling web pages in web development with Node JS, Express, and EJS. In this article, we will explore the process of including CSS in such projects to enhance the visual appeal and user experience.

Steps to include CSS files using NodeJS, ExpressJS, and EJS:

Step 1: let’s create a new NodeJS project. Open your terminal and run the following commands:



npm init -y

Step 2: Install the necessary package in your file using the following command.

npm install express ejs

Project Structure:

Project Structure

The updated dependencies in the package.json file will look like this.



"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1"
}

Here, we will demonstrate how to include CSS files using Node.js, Express, and EJS




// app.js
 
// Required modules
const express = require('express');
const path = require('path');
 
// Create Express app
const app = express();
 
// Set up static file serving
app.use(express.static(path.join(__dirname, 'public')));
 
// Set up EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
 
// Define route for the homepage
app.get('/', (req, res) => {
    res.render('index');
});
 
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});




<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Website</title>
  <link rel="stylesheet" href="/styles/main.css">
</head>
 
<body>
  <h1>Welcome to My Website</h1>
  <p>This is a sample paragraph.</p>
</body>
 
</html>




/* public/styles/main.css */
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
}
 
h1 {
    color: #b00a0a;
}
 
p {
    color: #7051e9;
}

Start your application using the following command.

node server.js

Output:

CSS applied to EJS


Article Tags :