How to install EJS view template engine in express.js Node project? 1


 

Step 1:

Check the node & npm version first by the following code:

 

npm -v

node -v

 

Step 2:

If node & npm is already installed, then write the following command in the terminal to install express:

 

npm install --save express

or

npm i express

 

 

Now include the following code in project_folder/index.js:

 

const express = require('express');

const app = express();

 

 

Now express has been installed.

 

Step 3:

Now install EJS by running the following command in the terminal:

 

 

npm install ejs

or

npm i ejs

 

Step 4:

Now create a folder with name views in the root of your project. And create home.ejs file inside the views folder.The project directory should look like the below:

 

project_folder

node_modules

views

home.ejs

index.js

package-lock.json

package.json

 

Now set the default template engine by including the following line in the root index.js file of the project:

 

index.js:

 

app.set('view engine','ejs');

app.get('/',(req,res)=>{

res.render('home') // calling the home.ejs from of views folder to load view

})

 

 

Now write simple html code in home.ejs :

<h1> Hello EJS!!</h1>

 

Step 5: 

If nodemon is installed in your project then run the following command in the terminal:

 

 

 

npm run nodemon

if nodemon is not installed, then run the default command to start the project:

node index.js

 

 

Step 6:

Now run the project using your port number, for example:

http://localhost:3000/

 

Note: 3000 is your port number. You can replace it with your own.

The output should be :

 

 

Hello EJS!!