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

使用ES6 import/export无法导入router模块的问题排查

问题解决:ES6模块导入找不到模块的问题

核心原因

你遇到的问题源于两个关键点:

  • ES模块与CommonJS导出语法不兼容
  • ES模块导入路径必须包含完整文件扩展名

具体修改方案

1. 修正路由文件的导出语法

在availability.js中,将CommonJS的导出方式替换为ES模块的默认导出:

import express from "express"
const router = new express.Router()

router.get(`/verify/email/:email`, async (req, res) => {
  // 业务逻辑
})

router.get(`/verify/username/:username`, async (req, res) => {
  // 业务逻辑
})

// 替换原来的module.exports为ES默认导出
export default router

2. 修正导入路径的扩展名

在app.js中,导入路由时需要加上完整的.js扩展名:

import express from "express"
import("./db/mongoose")
const app = express()

// 添加.js扩展名
import availabilityRouter from "./routers/availability.js"

// 可选:将CommonJS导出替换为ES规范导出
export default app

补充说明

当你的package.json中设置了"type": "module"后,Node.js会把所有.js文件解析为ES模块,此时:

  • 必须使用ES模块的export/import语法,避免和CommonJS的module.exports/require混合使用
  • 导入本地模块时必须指定完整的文件扩展名(.js、.mjs等),不能像CommonJS那样省略

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:36:21