How to Access ENV Variables in JavaScript and Sass

Posted January 30, 2021 in Blog, Laravel

How to Access ENV Variable in JavaScript and Sass

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:
require('dotenv').config();

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 + '\';'
})

2 Replies to “How to Access ENV Variables in JavaScript and Sass”

In addition to using the dotenv package I can recommend the tool https://github.com/dotenv-linter/dotenv-linter. It’s a lightning-fast linter for .env files. It can check, fix and compare .env files. Maybe it would be useful for you.

Reply

Thank you for the tip 😊 It’s certainly a good utility.

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *