I am unable to load the env file via start script in my package.json
file because of which I am not able to work on my project, earlier with all these stated settings it used to work fine.
package.json
file:
"scripts": {
"start:dev": "node --loader ts-node/esm --env-file=./env/.env.dev source/server.ts",
}
Env file:
AUTHENTICATION_API_URL="http://localhost:4000/login"
GRAPHQL_API_URL="http://localhost:4000/graphql"
HOST="localhost"
NODE_ENV="development"
DB_PORT="3306"
SRVR_PORT="5000"
DB_PWD= my_secret
DB_NAME= my_secret
DB_USR="root"
DB_LOGGING=false
server.ts
:
const port =
process.env.NODE_ENV === "production" ? process.env.SRVR_PORT || 80 : 4000;
console.log("{}}}}}}}}}}}}}}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{");
console.log(port);
console.log("{}}}}}}}}}}}}}}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{");
tsconfig.json
file:
{
"compilerOptions": {
"esModuleInterop": true,
"lib": ["es2020"],
"module": "NodeNext",
"preserveConstEnums": true,
"moduleResolution": "NodeNext",
"strict": true,
"sourceMap": false,
//"target": "es2022",
"target": "es6",
"types": ["node"],
"outDir": "dist",
"rootDir": "./",
"experimentalDecorators":true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true
},
"ts-node": {
"esm": true,
// needed for build system and auto reload
"swc": true,
// https://github.com/TypeStrong/ts-node/issues/422
"experimentalSpecifierResolution": "node"
},
"include": ["source/**/*", "package.json"],
"exclude": ["node_modules"],
}
It keeps showing me this error :
node --loader ts-node/esm --env-file=./.env/.env.dev source/server.ts
node: bad option: --env-file=./.env/.env.dev
I do not how to resolve this.
This is because Node.js does not natively support the --env-file option. This option is not a standard Node.js CLI flag, which is why you're seeing the bad option error.
To load environment variables from a .env
file in a Node.js project, you typically use the dotenv package.
npm install dotenv ts-node
Update your script:
"scripts": {
"start:dev": "node -r dotenv/config --loader ts-node/esm source/server.ts dotenv_config_path=./env/.env.dev"
}
Update server.ts
:
import dotenv from 'dotenv';
// Load the .env file
dotenv.config({ path: './env/.env.dev' });
const port = process.env.NODE_ENV === "production" ? process.env.SRVR_PORT || 80 : 4000;