Node.js中使用export导出Pug编译函数时报Unexpected token错误
问题原因
Node.js 默认使用 CommonJS 作为模块规范,该规范不支持 ES 模块的 export 语法,因此直接使用 export 导出函数会触发语法错误。
可选解决方法
- 方案1:沿用 CommonJS 规范
修改导出逻辑为 CommonJS 写法,替换原有export function相关代码:
// 原有函数逻辑保持不变 function compile(relativeTemplatePath, data){ let absoluteTemplatePath = process.cwd() + '/src/views/' + relativeTemplatePath + '.pug'; let compiledTemplate = compileFile(absoluteTemplatePath)(data); return compiledTemplate; }; // 改为CommonJS导出 module.exports = { compile };
同时对应导入侧的代码也使用 CommonJS 写法:
const { compile } = require('./pug.compiler.js');
- 方案2:切换为ES模块(ESM)规范
在项目根目录的package.json中新增配置项"type": "module",此时Node.js会将所有.js文件识别为ESM模块,原有export语法可正常运行。
注意需要同步修改导入语法为ESM规范:
原有导入pug的代码const {compileFile} =require('pug');改为:
import { compileFile } from 'pug';
导入该工具的代码也同步改为:
import { compile } from './pug.compiler.js';
内容的提问来源于stack exchange,提问作者grootste
相关产品推荐
相关产品推荐

