Laravel-mix: Is .env nested variables working in Mix file?

Created on 10 Oct 2018  路  6Comments  路  Source: JeffreyWay/laravel-mix

  • Laravel Mix Version: 2.1.4
  • Node Version: 9.11.2
  • NPM Version: 5.6.0
  • Yarn Version: 1.7.0
  • OS: macOS Mojave

Description:

Hello,

I'm wondering if .env nested variables are intended to work in Mix file?

Steps To Reproduce:

Considering a .env variable APP_URL with value http://laravel.wip

  • In .env, add the following variable: MIX_BROWSERSYNC_PROXY="${APP_URL}"
  • In webpack.mix.js, add the following line: console.log(process.env.MIX_BROWSERSYNC_PROXY)
  • Expected output: http://laravel.wip
  • Output: "${APP_URL}"

Thanks in advance! :)

All 6 comments

Mix is using this library under the hood

https://www.npmjs.com/package/dotenv

It looks like this library doesn't support nested variable like the PHP library used by Laravel does

https://github.com/vlucas/phpdotenv#nesting-variables

However a fresh version of Laravel installed using Laravel installer generates the following .env file:

...
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
...

Is the issue on Laravel default .env file? It looks weird, so I assume that there is a trick on Laravel Mix side :D

The line

console.log(process.env.MIX_BROWSERSYNC_PROXY)

Will be replaced by webpack if you place in your source code for example app.js

Yep, but not in the webpack.mix.js :/ This may be useful, for example to automatically set Browsersync proxy value to APP_URL value:

In .env:

APP_URL=http://laravel.wip
...
MIX_BROWSERSYNC_PROXY="${APP_URL}"

In webpack.mix.js:

mix.browserSync(process.env.MIX_BROWSERSYNC_PROXY);

Right, env vars will not be available in your webpack.mix.js file. They are only available as part of your webpack build.

I ran into this too, with the exact same use case for BrowserSync. The part that adds the most confusion is that MIX_ variables can be accessed by default inside webpack.mix.js, just not the expanded variable syntax.

My workaround was to add this to webpack.mix.js:

const expand = require('dotenv-expand');
expand(require('dotenv').config());

And then access the expanded MIX_ variables normally. I don't know if there are any downsides to doing it this way, but since these packages are already used by Mix you don't have to install anything extra.

Edit: Thanks to this comment, I realized you can just access process.env.APP_URL from webpack.mix.js

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Micaso picture Micaso  路  3Comments

dtheb picture dtheb  路  3Comments

wendt88 picture wendt88  路  3Comments

pixieaka picture pixieaka  路  3Comments

mstralka picture mstralka  路  3Comments