How to Access ENV Variables in JavaScript and Sass

Posted January 30, 2021 in Blog, Laravel

Recently we faced an issue with our CDN and environments, we needed both our online staging and production assets to be stored to their respective CDN paths. In order to this, we had to figure out how to access ENV variables in JavaScript and Sass files by passing them through Laravel Mix.

Production goes to <cdn-url>/production while staging is <cdn-url>/staging to avoid the indeed issue of overwriting each other.

Welcome to DotENV

To our luck there is already an NPM package out there which solves the Laravel Mix, or Webpack, part of the issue:

npm install --save-dev dotenv

Implement it by edit webpack.mix.js

// Below this line "const mix = require('laravel-mix');" add:

Now the ENV-variables are accessible through process.env, for instance, we had to define the fonts path:

mix.config.fileLoaderDirs.fonts = process.env.CND_PATH +'/fonts'

But Wait… What About Sass?

Since Sass allows us to implement variables in CSS we can pass specific variables from Webpack down to our Sass by modifying the Sass-property:

.sass('resources/sass/app.scss', 'public/css', {
    additionalData: '$CDN_PATH:\'' + process.env.CDN_PATH + '\';'