I have a typescript project structure like this:
root/
app/
index.ts
config/
.env.dev
Inside index.ts, I want to call dotenv.config()
with the path pointing to the .env.dev
file to configure it:
import * as dotenv from 'dotenv';
import path from 'path';
// set __dirname, yada yada yada
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// NODE_ENV is defined manually to NODE_ENV=dev
const dotenvPath = path.join(__dirname, '../', `config/.env.${process.env.NODE_ENV}`);
dotenv.config({
path: dotenvPath,
});
console.log(`dotenvPath: ${dotenvPath}`)
console.log(`${process.env.SOMEVAR_INSIDE_ENVDEV_FILE}`) // <-- undefined
However, when I try to use process.env.SOMEVAR_INSIDE_ENVDEV_FILE
, it is undefined.
The line console.log(`dotenvPath: ${dotenvPath}`)
outputs:
dotenvPath: C:\Users\myuser\path\to\project\.build\config\.env.dev
However, .build\config\
seems to not exist. This is my tsconfig.json
:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"outDir": "./build",
"rootDir": "./app"
},
"exclude": ["node_modules"]
}
Adding the following tag after "exclude"
tag:
"include": [
"./config/*",
],
gives me a weird error that I could not find much about: Error: [{"messageText":"No inputs were found in config file 'tsconfig.json'. Specified 'include' paths were '[\"./config/*\"]' and 'exclude' paths were '[\"node_modules\"]'.","category":1,"code":18003}]
. Only resource I found was this, but it doesn't make much sense in my case, because I find nothing wrong with what I did.
How can I force typescript to include my ./config/.env.dev
file into the transpilation process, so that I can access it during runtime?
Typescript only transpiles Typescript files and potentially Javascript files. If you just want to write a script that copies a file if it has changed, this seems like a good problem for adopting a build tool like Make.