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

Nest.js生产环境运行dist/main.js时报错问题求助

Fix for Nest.js Build Success but Runtime Error with TypeORM Entities

Hey there, let's break down what's going on here. The core issue lies in your TypeORM entity configuration—you're pointing to .entity.ts files, but after running npm run build, those TypeScript files get compiled to JavaScript (.js) in the dist directory. When you try to run node dist/main.js, the app can't locate the .ts files anymore, which triggers the error.

Here's how to fix this step by step:

1. Update the Entity Path for Both Environments

Change your entities array to dynamically target the correct file extension based on whether you're in development or production mode. This ensures it works both with npm run start (dev mode using .ts) and node dist/main.js (production using .js):

entities: [
  process.env.NODE_ENV === 'production'
    ? __dirname + '/../**/*.entity.js'
    : __dirname + '/../**/*.entity.ts'
]

Alternatively, you can use a glob pattern that matches both extensions for a simpler setup:

entities: [__dirname + '/../**/*.entity{.ts,.js}']

2. Verify Your Build Output

Double-check that your dist folder contains the compiled .entity.js files. If they're missing, confirm your tsconfig.json includes the directories where your entities live. Ensure the include array covers your source files:

{
  "include": ["src/**/*"]
}

3. Quick Additional Checks

  • Relative Path Accuracy: Make sure __dirname is correctly pointing to the right directory. In the compiled dist folder, __dirname refers to the location of main.js, so the ../ should properly navigate back to your compiled entity files.
  • Environment Variable Setup: If using the environment-based path check, set the production flag when running the app: NODE_ENV=production node dist/main.js

This should resolve the runtime error. Dev mode works because Nest uses ts-node to handle .ts files directly, but the compiled build needs to reference the .js versions of your entities.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:58:12