Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get env variable in scss

I want to get one env variable data in my scss file by using mix in Laravel. How to get that?

I have used something like this. But this one is a URL, so, it is not getting.

mix.sass('resources/assets/sass/main-v2.scss', 'public/css', {
    data: `awsUrl: "${(process.env.MIX_AWS_S3_CDN)}" ;`
})
like image 832
S K R Avatar asked Jul 19 '19 11:07

S K R


3 Answers

There is a simple way to do it. Follow steps as below,

Correct me if wrong, you want to pass an URL to main-v2.scss file as a variable.

  1. Add a variable in your .env file as below,

    MIX_AWS_URL='https://your-aws-endpoint.xyz?v1'

  2. In your webpack.mix.js file, add as below,

        mix.sass('resources/assets/sass/main-v2.scss', 'public/css', {
           // Use "data" for prependData instead of data.
           data: '$awsUrl:\'' + process.env.MIX_AWS_URL + '\';'
           // single quotes needs to be added as your URL contains : (colon) so, it may create an issue. Better to escape.
        })
    
  3. Next, you can directly use $awsUrl variable in your main-v2.scss file as below.

        // Pass to function
        @import url($awsUrl);
    
       // Or assign to another variable
       $myVariable : $awsUrl;
    

That's it!


Update

For Laravel 8+, use below in step 2,

mix.sass('resources/assets/sass/main-v2.scss', 'public/css', {
   prependData: '$awsUrl:\'' + process.env.MIX_AWS_URL + '\';'
   // single quotes needs to be added as your URL contains : (colon) so, it may create an issue. Better to escape.
})
like image 149
Vaibhavraj Roham Avatar answered Oct 21 '22 12:10

Vaibhavraj Roham


I only got it working requiring dotenv myself inside webpack.mix.js.

This should work:

let mix = require('laravel-mix');
require('dotenv').config();

mix.sass('resources/assets/sass/main-v2.scss', 'public/css', {
    data: '$awsUrl:\'' + process.env.MIX_AWS_URL + '\';'
})
like image 29
Remul Avatar answered Oct 21 '22 10:10

Remul


for those who are using laravel 8+ the parameter data changed to prependData

  mix.sass('resources/assets/sass/main-v2.scss', 'public/css', {
       prependData: "$awsUrl:'" + process.env.MIX_AWS_URL + "';"
    })
like image 29
Mansour Alnasser Avatar answered Oct 21 '22 12:10

Mansour Alnasser