There are times when we wanted to pass .env vars over to javascript, regardless of what type of framework is being used.
We tried the following methods.
- Passed to a js var wrapped inside a laravel blade file - which works but when viewed over the browser all the vars will be visible.We have stumbled over code where the js is embedded
- One step ahead, we used jeffery way's re-usable package PHP-Vars-To-JS
- One step further, we started passing the values over the meta attributes instead of cluttering the .blade.php files
- One more step ahead, probably this is the cleaner way - as .env is just another hidden file, why not let webpack and node read it !
So we took the below approach
- Use a .env parser, in this case we used DotEnv
- Use webpack's DefinePlugin
- Parse each key of the .env file and define a constant over the webpack.mix.js - In our project we are using laravel and laravel-mix, this config might vary depending on the project and it's tech. stack
So when combined all the three, we set-up our project like the image below.