node.jsexpressejs

Express and ejs: using ejs with other file extensions: require not working


According to the docs, the line:

app.engine('html', require('ejs').renderFile)

should get express to process .html files as if they were .ejs which was my first simple test to have ejs work with alternative file extensions

However, when I include this in my index.js node immediately crashes with the error:

ReferenceError: require is not defined in ES module scope...

I'm using:

I have done a lot of searching but can't seem to fix this, index.js looks like

    import express from "express";
    import bodyParser from "body-parser";
 
    const app = express();
    const port = 3001;
 
    app.engine('html', require('ejs').renderFile);
    // app.set('view engine', 'html')
    app.use(express.static("public"));
 
    const currentYear = new Date().getFullYear();
 
    app.use(bodyParser.urlencoded({ extended: true }));
 
    app.get("/", (req, res) => {
 
      const data = {
        title: "welcome page",
        year: currentYear,
      };
      res.render("index.html", data);
    });

    app.listen(port, () => {
      console.log(`Listening on port ${port}`);
    });

NOTE: Ok, problem is probably(?!?) as I am using type module for my project, but there should be a way around this while still keeping type module


Solution

  • As you're using module, just don't use require:

    Try:

    import ejs, {renderFile} from 'ejs'; // or just ejs + ejs.renderFile
    
    app.engine('html', renderFile); // or ejs.renderFile