Skip to content

Instantly share code, notes, and snippets.

@psgganesh
Last active October 16, 2017 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psgganesh/fcd91f3e878b7f10ed55e280f055c81c to your computer and use it in GitHub Desktop.
Save psgganesh/fcd91f3e878b7f10ed55e280f055c81c to your computer and use it in GitHub Desktop.
Pass that .env to JS !

Cleaner way to pass over .env vars to javascript ( Laravel .env -> .js )

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

  1. Use a .env parser, in this case we used DotEnv
  2. Use webpack's DefinePlugin
  3. 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.

RAW Version of image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment