Are you using or planning to use StencilJS for web component/application development? Have you ever required something that is environment specific & needs to be replaced in your final build (at compile time)?
So without any further delay let’s begin:
How Environment Variables are useful?
- We can have something that is specific to some particular environment build(dev/stage/prod), e.g. API host, hosted Style URLs, log levels (debug, error, trace, all)
- Easy to manage configuration values using system/user variables or file
What do we want to achieve?
- Read values from Operating System’s Environment Variables or a .env File
- Replace some keys with these values in our source code before building
Integrating Environment Variable read & replace process
I suppose you have already created a Stencil project using npm init stencil
1. Go to the project root & install rollup-plugin-dotenv as dev dependency
or if you use yarn
yarn add rollup-plugin-dotenv @types/node -D
2. Open stencil.config.ts file in your preferred code editor
Import rollup-plugin-dotenv & use it under plugins as shown below
3. You are all set to use Environment variables now
Creating Environment Variables
- You can either put your environment variables in OS’s system/user variables
- or can create .env file at project root & put the environment specific values in it
Using Environment Variables inside the component
It is pretty straight forward: access any value using process.env.SOMETHING
Hurray, we have used environment driven values in our Stencil Component
Things to remember
- @types/node typing must be installed (mentioned earlier) to avoid IDE/compilation error report on process.env thing as it is unknown to stencil & typescript syntax!
- Whenever you add/modify some env variable you will need to rebuild or restart your development server
- .env file values take precedence over OS system/user variables. So if some variable is present at both the places, one that is contained inside .env file will be used
- plugin first looks for a variable in .env file placed in project root & if not found looks in systems environment variables
- Never commit .env file, as it is environment specific thing & should be created as per the requirement. You can commit a sample .env.example file to guide anyone who needs to create .env file or system variables
I hope you enjoyed this story. If you liked it, please show your love with some claps. Stay tuned for some more exciting stuff containing my latest learnings.
😊 Keep Learning, Keep Sharing, & Keep Rocking 😊