Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module 'hbs', express-handlebars

I am trying to use express-handlebars view engine for express and I keep getting the following error:

Error: Cannot find module 'hbs'
    at Function.Module._resolveFilename (module.js:538:15)
    at Function.Module._load (module.js:468:25)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at new View (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\view.js:81:14)
    at Function.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\response.js:1008:7)
    at C:\Users\WilPrim\Desktop\node-app\routes\routes.js:5:6
    at Layer.handle [as handle_request] (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\WilPrim\Desktop\node-app\node_modules\express\lib\router\route.js:137:13)

Here is my Code:

const express = require("express");
const bodyParser = require("body-parser");
const hbs = require("express-handlebars");
const router = require("./routes/routes");

//set up express app
var app = express();

app.use(bodyParser.json());

app.set('view engine', 'hbs');
app.set('views', './views');
app.set('view options', {layout: './layouts/layout'});

app.use(router);
like image 224
Wil Prim Avatar asked Jan 11 '18 16:01

Wil Prim


2 Answers

According to the express-handlebars documentation, you have to setup and register the view engine manually:

var express = require('express');
var exphbs  = require('express-handlebars');

var app = express();
var hbs = exphbs.create({ /* config */ });

// Register `hbs.engine` with the Express app.
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

// ...still have a reference to `hbs`, on which methods like `loadPartials()`
// can be called.

Looking a little bit further down in the documentation, looks like you can still use the .hbs extension with a bit of configuration:

var express = require('express');
var exphbs  = require('express-handlebars');

var app = express();

app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
like image 182
Xavier Avatar answered Nov 15 '22 03:11

Xavier


use command -- sudo npm link hbs

like image 22
Ankit Gaur Avatar answered Nov 15 '22 03:11

Ankit Gaur