Joel Peltonen
Joel Peltonen

Reputation: 13432

How can I use environment variables in node-sass .scss files?

I want a configurable default color variable maintained in an .env file. For example I would want an .env file that contains

PRIMARY=red

And a _variables.scss file that contains

$primary: ${process.env.PRIMARY}

And an SCSS file that contains

.my-class { color: $primary; }

And components where I use the stylesheets that contains

import './MyComponent.scss';

Is this possible? If not, what alternatives would I have?

Upvotes: 11

Views: 10171

Answers (2)

Hossein Rashno
Hossein Rashno

Reputation: 3469

Robert's answer was a good clue but it didn't work for me. I spent an hour fixing my Webpack config and I just want to share the result here so no one else wastes their time here.

You should create your function in the sass-loader's sassOptions object like below: (using node-sass-utils is not required)

// Import node-sass at the top of your config file
const nodeSass = require('node-sass');


// Add this object to the sass-loader options object
sassOptions: {
    functions: {
        "env($variable)": variable => {
            const value = variable.getValue();
            const envValue = process.env[value]
            const sassValue = new nodeSass.types.String(envValue); 
            return sassValue;
        }
    }
}

Then you can use any env variables in your SASS files like below:

.my-class {
  color: env('ENV_VAR_NAME');
}

Upvotes: 2

Robert Moore
Robert Moore

Reputation: 2582

Assuming you are using webpack and sass-loader (you will need to eject, which I think is worth it if you don't mind extra files and more dependency updating), modify your webpack.config.js file like this:

const { castToSass } = require('node-sass-utils');

module.exports = {
...
  {
    test: /\.scss$/,
    use: [{
        loader: "style-loader"
    }, {
        loader: "css-loader"
    }, {
        loader: "sass-loader"
        options: {
          functions: {
            "env($variable)": variable => castToSass(process.env[variable]);
          }
        }
    }]
  }

Now you could make a file _variables.scss like this:

$primary: env('primary');

If this doesn't work or you need more flexibility, check out the article I based it off of and feel free to edit my answer.

Upvotes: 10

Related Questions