javascriptnode.jsexpresshandlebars.jsviewengine

Handlebars not a function error in express-handlebars


my code,got from a website

const express = require('express');
const app = express();
const port = 3000;
//Loads the handlebars module
const handlebars = require('express-handlebars');
//Sets our app to use the handlebars engine
app.set('view engine', 'handlebars');
//Sets handlebars configurations (we will go through them later on)
app.engine('handlebars', handlebars({
layoutsDir: __dirname + '/views/layouts',
}));
app.use(express.static('public'))
app.get('/', (req, res) => {
//Serves the body of the page aka "main.handlebars" to the container //aka "index.handlebars"
res.render('main', {layout : 'index'});
});

app.listen(port, () => console.log(`App listening to port ${port}`));

showing an error that

app.engine('handlebars', handlebars({
                         ^

TypeError: handlebars is not a function

How can i solve these problem tried lots of solutions but still not working

My directory looks like

enter image description here


Solution

  • const express = require('express');
    const app = express();
    const port = 3000;
    //Loads the handlebars module
    const handlebars = require('express-handlebars');
    
    

    You can setup handlebar as

    var hbs = handlebars.create();
    app.engine("handlebars", hbs.engine);
    app.set("view engine", "handlebars");
    app.use(express.static(__dirname + "/views"));
    
    
    app.get('/', (req, res) => {
    //Serves the body of the page aka "main.handlebars" to the container //aka "index.handlebars"
    res.render('main', {layout : 'index'});
    });
    
    app.listen(port, () => console.log(`App listening to port ${port}`));