Laravel with Vue.js and environmental variables

0/5 (0 Reviews)

Tóm Tắt

It’s just a tip for someone who;

  1. Uses Laravel, Mix and Vue.js,
  2. Looking for a .env implemantation for a day, a whole day,
  3. Forks one and tries to improve it with dynamic .env file names,
  4. Finds out require() function with webpack can’t use variable module names, because of build-time confusions of it’s nature etc.
  5. Is already aware of Laravel’s .env functionality and asks himself what about that one?
  6. Then figures out there is even a section in their documentation about that!

So basically, just add whatever environmental variable to your .env files with the prefix of MIX_

You don’t even have to retype your existing variable values, just use them as they are:

APP_URL=http://127.0.0.1:8000
MIX_APP_URL="${APP_URL}"​

Or you may mix them with new variables:

APP_URL=http://127.0.0.1:8000
MIX_GRAPHQL_URI="${APP_URL}/graphql"

Finally, use them anywhere in your client app:

const httpLink = new HttpLink({
    uri: process.env.MIX_GRAPHQL_URI
});
Vue.axios.defaults.baseURL = process.env.MIX_APP_URL;

And you can always test your environment with NODE_ENV

if ( process.env.NODE_ENV == 'production' ) {
     ...do things in production mode
} else {
     ...or the other way
}

Note that you don’t define NODE_ENV in your .env file, it’s already set and value depends on very webpack build.

Tags