Paulund
2018-10-06 #laravel

How To Use .env Variables In Webpack.js

In this tutorial we're going to learn how we can use our .env variables inside the webpack.js config. The benefit of this is that we can now build the frontend assets based off variables in the application.

This is perfect for the example of when you have a different javascript file based of an variable. Maybe you have a cross region application where you have a uk.js file and a us.js file, you'll use the APP_REGION environment variable to decide which javascript file to compile.

Laravel Mix

If you're using Laravel mix then there's already a nice way you can include environment variables in your javascript. All you have to do is prefix the environment variable with MIX_.

Therefore you can just use MIX_APP_REGION or if you also need a APP_REGION variable.

APP_REGION=uk
MIX_APP_REGION=${APP_REGION}

Now you have use this in your javascript by using process.env.MIX_APP_REGION

But these variables are not available in your webpack.mix.js file, therefore you can't compile your assets based off environment variables.

Laravel Mix Environment Variables

Using Variables In webpack.mix.js

The solution to get these variables in your webpack.mix.js is to use a package called dotenv, which is already installed by Laravel mix.

Then you can add this to the top of your webpack.mix.js file.

require('dotenv').config();

This will add your environment variables to be accessed in the process variable.

process.env.APP_REGION

Now we can use this variable for the file when compiling the javascript.

mix.js('resources/js/' + process.env.APP_REGION + '.js', 'public/assets/js/region.js').version()