how to use static files in express with ejs
Using Static Files in Express with EJS
To use static files in Express with EJS, you can follow these steps:
- Install the necessary dependencies:
Install Express and EJS by running the following command in your terminal:
npm install express ejs --save
Set up your Express application:
- In your index file (e.g.,
index.js
), require the necessary dependencies at the top of the file:javascript const express = require('express'); const app = express();
Set the view engine to EJS by adding the following line:
javascript app.set('view engine', 'ejs');
Create a
public
directory:- In your project's root directory, create a directory named
public
. This directory will be used to store your static files, such as CSS, JavaScript, and images.
Serve the static files using the
express.static
middleware:- Add the following line of code after setting up your Express application:
javascript app.use(express.static('public'));
This line tells Express to serve the static files from the
public
directory.Use the static files in your EJS templates:
- In your EJS templates, you can reference the static files using the following syntax:
html <link rel="stylesheet" href="/css/style.css"> <script src="/js/script.js"></script> <img src="/images/logo.png" alt="Logo">
- Replace
css/style.css
,js/script.js
, andimages/logo.png
with the actual paths to your static files.
That's it! Now, when you run your Express application, it will serve the static files from the public
directory, and you can use them in your EJS templates.