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
相关产品推荐
相关产品推荐

