I’m working on a Node.js + Express project using TypeScript with the "module": "nodenext" option in tsconfig.json. The issue is that my files execute out of order
Project Setup
tsconfig.json:
{
"compilerOptions": {
"target": "ESNext",
"module": "nodenext",
"moduleResolution": "nodenext",
"outDir": "dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"baseUrl": "./",
"typeRoots": ["./node_modules/@types", "./src/@types"],
"types": ["node", "express"],
"paths": {
"#src/*": ["src/*"]
}
},
"include": ["**/*.ts"],
"exclude": ["node_modules", "dist"]
}
package.json
{
...
"main": "server.ts",
"type": "module",
"scripts": {
"lint": "eslint src --ext .ts",
"lint:fix": "eslint src --ext .ts --fix",
"dev": "nodemon --watch . --ext ts --exec tsx server.ts",
"build": "tsc",
"start": "node server.js"
},
"license": "ISC",
"dependencies": {....},
"devDependencies": {....},
"imports": {
"#src/*": "./src/*"
}
}
./server.ts (Entry Point)
console.log('server.ts is executing');
import dotenv from 'dotenv';
dotenv.config({ path: './config.env' });
console.log('ENV:', process.env.NODE_ENV);
import mongoose, { MongooseError } from 'mongoose';
import { server } from '#src/app.js';
......
./src/controllers/socketController.ts
console.log('socketMessageController.ts is executing');
import appConfig from '#src/config/appConfig.js';
import userSockets from '#src/helper/socketMap.js';
.....
Issue
When I run the project using: npm run dev
The output is:
This means socketMessageController.ts is executing before server.ts, causing process.env to be undefined in that file. Right now, I am hardcoding environment variables as a workaround.
Expected Behavior:
server.ts should execute first, loading environment variables before any other files that depend on them.
Other modules should get process.env properly populated.
