Installing EJS with npm
To install and set up EJS (Embedded JavaScript) in a Node.js project using npm, follow these steps:
1. Initialize Your Node.js Project
If you haven't already created a Node.js project, start by initializing it:
Create a Project Directory:
mkdir my-ejs-project cd my-ejs-project
Initialize a New Node.js Project:
Run the following command to generate a
package.json
file with default settings:npm init -y
2. Install EJS
EJS can be installed via npm. To add EJS to your project, use the following command:
npm install ejs
This command performs the following:
- Downloads EJS: It fetches the EJS package and its dependencies.
- Updates
package.json
: It adds EJS as a dependency in yourpackage.json
file. - Updates
package-lock.json
: It records the exact version of EJS and its dependencies to ensure consistent installations.
3. Set Up EJS in Your Express Application
If you're using Express.js, you'll need to configure it to use EJS as the view engine:
Install Express (if not already installed):
npm install express
Configure Express to Use EJS:
Create an
app.js
file (or modify it if it already exists) to set EJS as the view engine. Here's an example setup:const express = require('express'); const path = require('path'); const app = express(); // Set EJS as the view engine app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Define a route app.get('/', (req, res) => { res.render('index', { title: 'Home Page' }); }); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
app.set('view engine', 'ejs')
: Configures Express to use EJS as the templating engine.app.set('views', path.join(__dirname, 'views'))
: Specifies the directory where your EJS templates will be stored.
Create EJS Templates:
Create a
views
Directory:Inside your project directory, create a
views
directory to hold your EJS templates:mkdir views
Add an EJS Template:
Inside the
views
directory, create anindex.ejs
file: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><%= title %></title> </head> <body> <h1>Welcome to <%= title %></h1> </body> </html>
This template uses EJS syntax to embed JavaScript logic and variables (
<%= title %>
) directly within the HTML.
4. Run Your Application
Start your Express server by running:
node app.js
Navigate to http://localhost:3000
in your web browser to see the rendered EJS template.
Summary
- Initialize Project: Create a Node.js project using
npm init -y
. - Install EJS: Run
npm install ejs
to add EJS to your project. - Configure Express: Set EJS as the view engine in your Express application.
- Create Templates: Add EJS templates in the
views
directory. - Run the Server: Start your server and view the rendered EJS templates in your browser.
This setup enables you to use EJS to dynamically generate HTML content based on data passed from your server.