Horje
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:

Screenshot-2024-02-25-111917

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

Javascript

// 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}`);
});

HTML

<!-- 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>

CSS

/* 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:

Screenshot-2024-02-25-112437

CSS applied to EJS




Reffered: https://www.geeksforgeeks.org


Express.js

Related
Mongo with Express Tutorial Mongo with Express Tutorial
Express JS Exercises, Practice Questions and Solutions Express JS Exercises, Practice Questions and Solutions
What is Express? What is Express?
Mastering JWT authentication in Express Mastering JWT authentication in Express
Express.js Tutorial Express.js Tutorial

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15