You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

express-handlebars报TypeError: handlebars is not a function错误的解决求助

解决express-handlebars报错:TypeError: handlebars is not a function

以下是我从网站获取的代码:

const express = require('express');
const app = express();
const port = 3000;
// 加载handlebars模块
const handlebars = require('express-handlebars');
// 设置应用使用handlebars模板引擎
app.set('view engine', 'handlebars');
// 配置handlebars参数
app.engine('handlebars', handlebars({
  layoutsDir: __dirname + '/views/layouts',
}));
app.use(express.static('public'))
app.get('/', (req, res) => {
  // 将main.handlebars内容渲染到index.handlebars容器中
  res.render('main', {layout : 'index'});
});

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

运行时触发如下错误:

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

TypeError: handlebars is not a function

项目目录结构如下:
项目目录结构

解决方案

这个错误是因为express-handlebars v4及以上版本的导出方式发生了变化,旧教程的写法仅适用于v3及更早版本。可以通过以下两种方式修复:

方案一:使用create()方法创建引擎实例

修改handlebars引擎配置代码,调用create()方法获取可用的引擎实例:

const express = require('express');
const app = express();
const port = 3000;
const handlebars = require('express-handlebars');

app.set('view engine', 'handlebars');
// 调用create()生成引擎实例,再取其engine属性
app.engine('handlebars', handlebars.create({
  layoutsDir: __dirname + '/views/layouts',
}).engine);

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.render('main', {layout : 'index'});
});

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

方案二:直接解构导入engine方法

从express-handlebars中直接导出engine函数用于配置:

const express = require('express');
const app = express();
const port = 3000;
// 解构导入engine方法
const { engine } = require('express-handlebars');

app.set('view engine', 'handlebars');
app.engine('handlebars', engine({
  layoutsDir: __dirname + '/views/layouts',
}));

app.use(express.static('public'))
app.get('/', (req, res) => {
  res.render('main', {layout : 'index'});
});

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

原因说明

express-handlebars在v4版本后,默认导出不再是可直接调用的函数,而是一个包含create方法的对象;同时也提供了独立的engine方法供直接使用。旧代码直接调用handlebars()的写法已不再适用,因此会抛出“不是函数”的错误。

内容的提问来源于stack exchange,提问作者ABIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:30:53