2

I am new to typescript and i built this simple mailer application, but the problem is that TypeScript is unable to read the file, when i put it in the src folder it was not copied in dist on build, when i put it outside the src folder and put the manual require just to test IDE did not showed me option for enventer image description here

and here is my directory tree

enter image description here

what causes that? i dont have a clue.

1 Answer 1

2

Node (or typescript) does not know how to import a .env file natively.

You probably want to install and configure the dotenv npm package

Then you just add this line to the file that boots your server:

require('dotenv').config()

And now your env vars are accessible at:

process.ENV.MY_VAR_HERE

Here's a decent article on environment variables and how a .env file works with them.

Sign up to request clarification or add additional context in comments.

11 Comments

i did install dotenv but the problem is that .env file is not recognized by typescript (btw i use import) but when i do that in JS it works
What do you "not recognized by typescript"? When you use the dotenv package, you don't import the .env file directly. Also, I believe that file names that start with a . are omitted from autocompleting imports in most code editors.
i know it is not imported directly i just wanted to know, if typescript could reach the file because in .config({}) i put "path" property. and if ide omits . from autocomplete why did not tsc copied .env file into build (dist)?
The whole point of a .env file is that those values are provided by the environment at runtime. So it should not ever be in the compiled build. In production those values should be set as proper environment variables in the OS that is hosting your server. The .env file is just a way to fake that in a project specific way during development. So I'm still not sure what you're asking, but I don't think it works the way you think does.
I AM NOT REQUIRING ENV FILE I AM REQUIRING DOTENV AND CONFIGURING IT WITH PATH SAME AS I DO IN TS BUT IT WORKS IN JS AND NOT IN TS
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.