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

TypeScript+Express构建后启动报错:Cannot use import outside a module

TypeScript + Express构建后运行报错 Cannot use import statement outside a module

本地执行npm run dev可正常开发,但npm run build生成dist文件夹后,运行npm start时抛出错误:

Cannot use import statement outside a module

相关配置文件如下:

package.json

{
  "name": "mm-api",
  "version": "1.0.0",
  "description": "project",
  "engines": {
    "node": "^20.10.0"
  },
  "main": "./dist/index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon",
    "build": "rm -f -r dist && tsc && tsc-alias",
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d ./src/entities/index.ts"
  },
  "keywords": [],
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.21",
    "@types/node": "^20.10.5",
    "express": "^4.18.2",
    "reflect-metadata": "^0.2.1",
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/morgan": "^1.9.9",
    "@types/node": "^18.6.4",
    "nodemon": "^3.0.2",
    "ts-node": "^10.9.2",
    "tsc-alias": "^1.8.8",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.3.3"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist/",
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "allowJs": true,
    "moduleResolution": "node",
    "importHelpers": false,
    "preserveConstEnums": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmit": false,
    "resolveJsonModule": true,
    "isolatedModules": false,
    "paths": {
      "@config/*": ["src/config/*"],
      "@config": ["src/config"],

      "@controllers/*": ["src/controllers/*"],
      "@controllers": ["src/controllers"],
    }
  },
  "include": ["./src/"],
  "exclude": ["**/node_modules"]
}

nodemon.json

{
  "ignore": ["node_modules"],
  "watch": ["./src/**/*", ".env"],
  "exec": "ts-node -r tsconfig-paths/register ./src/index.ts",
  "ext": ".ts, .js"
}

解决方案

1. 明确模块类型

在package.json中添加type字段,指定为CommonJS(与tsconfig的module配置一致):

{
  // ... 其他配置
  "type": "commonjs"
}

这能避免Node.js默认将文件识别为ES模块,导致import语法报错。

2. 清理重复依赖

dependencies和devDependencies中重复存在@types/express、@types/node,版本不一致可能干扰编译。删除devDependencies里的重复项:

"devDependencies": {
  "@types/morgan": "^1.9.9",
  "nodemon": "^3.0.2",
  "ts-node": "^10.9.2",
  "tsc-alias": "^1.8.8",
  "tsconfig-paths": "^4.2.0",
  "typescript": "^5.3.3"
}

3. 调整allowJs配置

如果项目中没有需要编译的JS文件,将tsconfig.json的allowJs设为false,防止意外编译含ES模块语法的JS文件:

"allowJs": false

4. 验证编译产物

重新执行npm run build,检查dist/index.js的语法,确认是CommonJS格式(开头有"use strict";、Object.defineProperty(exports, "__esModule", { value: true });)。如果仍出现import语句,排查src目录下是否有未被正确编译的JS文件。

5. 检查TypeORM生产配置

确保生产环境中TypeORM使用的是编译后的实体文件路径,避免引入未编译的TS文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:57:07