Nest.js生产环境运行dist/main.js时报错问题求助
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
__dirnameis correctly pointing to the right directory. In the compileddistfolder,__dirnamerefers to the location ofmain.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

