NodeJS 找不到模块'hbs',快速手柄

u0njafvf  于 2023-02-12  发布在  Node.js
关注(0)|答案(6)|浏览(190)

我尝试使用express-handlebar视图引擎进行express,但一直收到以下错误:

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)

这是我的代码:

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);
qzlgjiam

qzlgjiam1#

根据express-handlebarsdocumentation,您必须手动设置和注册视图引擎:

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.

在文档中再往下看一点,看起来您仍然可以使用.hbs扩展,但需要进行一些配置:

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

var app = express();

app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
fumotvh3

fumotvh32#

使用命令--sudo npm link hbs

a0x5cqrl

a0x5cqrl3#

您可能已将主文件夹命名为“express”,只需更改文件夹名称,删除“package.json”并再次尝试“npm install”,然后尝试“npm install express”“npm install hbs”

lf3rwulv

lf3rwulv4#

/* been using this format for some time now, never had problems */ 
// import system modules
const hbs = require('express-handlebars');
const express = require('express');
const app = express();

// configuring express-handlebars as hbs
app.engine('hbs', hbs.create({
    extname: 'hbs',
    defaultLayout: 'main'
}).engine)

// system(app) routes
app.get('/', (req, res, next)=>{
    res.render('home', {title: 'HBS TITLE'});
});

// system listening port
app.listen(8080);
neekobn8

neekobn85#

在终端上安装此模块--〉npm i hbs

luaexgnf

luaexgnf6#

尝试npm安装和npm审计修复多次然后在ex后运行服务器

相关问题