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

Node.js导入模块遇Unexpected token错误,添加type:module后服务无法启动求助

问题排查与解决

你遇到的问题根源是在ES模块环境下混用了CommonJS语法:当你在package.json中添加"type": "module"后,Node.js会将所有.js文件视为ES模块,此时不能再使用CommonJS的require()语法,必须统一使用ES模块的import语法。

具体修复步骤:

  1. 统一模块导入语法
    将测试文件中的require("supertest")改为ES模块的import:

    import request from "supertest";
    import app from "../app";
    
    describe("Test the root path", () => {
      test("It should response the GET method", () => {
        return request(app).get('/').then((res) => {
            expect(res.statusCode).toBe(200);
          });
      });
    });
    
  2. 确保测试框架支持ES模块
    如果你使用Jest作为测试框架,默认它会以CommonJS模式运行,需要修改配置让它支持ES模块:

    • 在项目根目录创建jest.config.js文件,添加如下配置:
      export default {
        transform: {},
        testEnvironment: 'node'
      };
      
    • 或者直接在package.json中添加Jest配置:
      "jest": {
        "transform": {},
        "testEnvironment": "node"
      }
      
  3. 检查Node.js版本
    确保你的Node.js版本不低于v14.13.0(或v12.20.0),更低版本对ES模块的支持存在局限性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:10:52