You need to enable JavaScript to run this app. Node.js中使用export导出Pug编译函数时报Unexpected token错误
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 06:24:02