Categories
JavaScript Answers

How to use HTML as the view engine in Express with JavaScript?

Spread the love

In Express.js, by default, the view engine is set to use a template engine such as EJS, Handlebars, Pug (formerly Jade), etc.

However, if you want to use plain HTML files as your views without any template engine, you can do so by configuring Express to use the html file extension and serve static HTML files.

Here’s how you can set up Express to serve static HTML files as views:

1. Install Express

If you haven’t already installed Express in your project, you can do so using npm:

npm install express

2. Set up your Express app

Create your Express app and configure it to serve static HTML files from a directory.

const express = require("express");
const app = express();

// Set the directory from which to serve static HTML files
app.use(express.static("public"));

// Set the view engine to use HTML files
app.set("view engine", "html");

// Set the directory where your HTML files are stored
app.set("views", __dirname + "/views");

// Define your routes
app.get("/", (req, res) => {
  // Render the 'index.html' file
  res.render("index");
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

3. Create your HTML files

Create HTML files in a directory specified in the views directory.

For example, if you set app.set('views', __dirname + '/views');, create an index.html file in the views directory.

4. Accessing HTML files

Your HTML files will be served as views when you access the routes defined in your Express app.

For example, accessing the root route (/) will render the index.html file.

Your directory structure might look like this:

project
│   app.js
└───views
    │   index.html

In this setup, Express will serve static HTML files from the views directory without any additional processing. You can use plain HTML, CSS, and JavaScript in your HTML files as needed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *