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

Node.js运行编译后的TypeScript代码时出现「SyntaxError: Cannot use import statement outside a module」错误的解决咨询

Node.js运行编译后的TypeScript代码时出现「SyntaxError: Cannot use import statement outside a module」错误的解决咨询

我正在用TypeScript构建一个Node.js应用,编译代码后,用npm start运行生成的JavaScript文件时遇到了下面的错误:

当我执行命令:

npm start

得到的错误是:

SyntaxError: Cannot use import statement outside a module

我的app.ts主文件:

import "reflect-metadata"

import express from 'express';
import dotenv from 'dotenv';
import { useExpressServer } from 'routing-controllers';
import { connectDB } from './config/db';
import { CONNECTED_MESSAGE } from './common';
import { ENV_DETAILS } from './env';


dotenv.config();

// Create an instance of an Express app
const app = express();

// Configure built-in middleware to parse various types of request bodies
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded


// Configure routing-controllers with the Express app
useExpressServer(app, {
  controllers: ENV_DETAILS.dirs.controllers
});

// Connect to the database and start the server
const port =  3000;
connectDB().then(() => {
  app.listen(port, () => {
    console.log(CONNECTED_MESSAGE.listenPort, `${port}`);
  });
});

我的package.json脚本部分:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node dist/app.js",
    "dev": "tsx src/app.ts",
    "build": "tsc && tsc-alias"
  },

我的tsconfig.json文件:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "resolveJsonModule": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "@src/*": [
        "src/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

环境信息

  • Node.js版本:20.12.2
  • npm版本:6.14.11

我期望npm start能正常执行编译后的代码,不抛出错误。请问我的配置有什么问题吗?或者我是不是漏掉了什么关键设置?该怎么解决这个错误?

备注:内容来源于stack exchange,提问作者M BHARATH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:13:07