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:

  1. Install the necessary dependencies:
  2. Install Express and EJS by running the following command in your terminal: npm install express ejs --save

  3. Set up your Express application:

  4. 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();
  5. Set the view engine to EJS by adding the following line: javascript app.set('view engine', 'ejs');

  6. Create a public directory:

  7. In your project's root directory, create a directory named public.
  8. This directory will be used to store your static files, such as CSS, JavaScript, and images.

  9. Serve the static files using the express.static middleware:

  10. Add the following line of code after setting up your Express application: javascript app.use(express.static('public'));
  11. This line tells Express to serve the static files from the public directory.

  12. Use the static files in your EJS templates:

  13. 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">
  14. Replace css/style.css, js/script.js, and images/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.

[1]