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

为什么Node.js中使用export导出模块会报Unexpected token 'export'错误

报错原因解释&解决方案

根本原因

Node.js 默认使用 CommonJS 模块规范,仅识别 require() 导入和 module.exports 导出语法,无法直接解析 ES 模块(ESM)的 export default 语法,因此运行时会抛出 Unexpected token 'export' 错误。

两种可选修复方案

方案1:统一使用 CommonJS 规范(改动最小,推荐)

直接修改产品数据文件的导出语句,将:

export default products

替换为 CommonJS 导出语法:

module.exports = products

原有 server.js 中 const products = require('./data/products') 的引入逻辑无需改动,即可正常运行。

方案2:切换为 ES 模块规范

如果你需要使用 ESM 语法,可以做两处调整:

  1. 在项目根目录的 package.json 中新增字段:
    {
      "type": "module"
    }
    
    该配置会告知 Node.js 项目内所有 .js 文件默认按 ESM 规范处理。
  2. 修改 server.js 中的引入逻辑,将 require 替换为 ESM 导入语法,注意需要补全文件后缀:
    import products from './data/products.js'
    

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

相关产品推荐
方舟 Agent Plan

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

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