Lets say I have created a directory, envExample
I want to use a library name envalid
in my project and log the value of my environment variable from .env
file with type validation. How do I do this with typescript code?
Envalid is a small library for validating and accessing environment variables in Node.js programs
create directory:
Initialise the new Node.js
project:
And this will create a package.json
file in the directory. And inspecting the package.json we get:
Add the envalid
to the project
This will create a packeage.json
, packeage-loc.json
file and node_modules
. Lets not look into the node_modules
folder right now. All that folder does it fetches the required code and functionality of the library we want to use in our code base.
And the package.json file has the reference of the library we have used in the codebase and the version of it:
Now we want to create our .env
file:
Now to organise our code we are going to use source directory:
inside the envConstants.ts
we add the following code:
envalid
uses theprocess.env
object to load environment variables, and the.env
file isn't automatically loaded intoprocess.env
by default.
Typescript will show an error on process
. Why? well typescript doesn’t know what the process is. We need to add the typescript functionality to our code. Run the following:
This will add the types of node. But what is the --save-dev
part in the command?
Lets explore the changes in our package.json
file in the envExample
directory?
—save-dev
This flag tells npm
to save the installed package as a development dependency. Development dependencies are packages only needed during the development (like testing, linters, or type definitions) and are not required for the application to run in production.
And lets look at the error in process
disappear. Your IDE now knows the types of the node processes
.
Now add the following in index.ts
:
Now if I were to run the node src/index.ts
it throws an error:
Why? Because we haven’t created the Typescript configuration file yet. Run the following on the root folder
This will add tsconfig.json
file to the codebase. Replace with followings:
now run the following command:
What is this npx
?
npx
npx
is a versatile tool that makes it easier to run project-specific binaries, use temporary tools, and avoid global installations, leading to cleaner and more maintainable code.
By running the command a dist
folder will be created. Inside the folder will be the compiled js files. Now if we run the following file we will see this:
Now we can update the package.json with the following script:
Now after any change in the code base simply run the following: