Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS conditional imports based on env variables using webpack (to use different themes per environment)

For my Vue website project using a single style sheet generated using Webpack from SASS I want to have:

Conditional SASS imports based on an env variable


EXAMPLE SETUP:

.env : So for instance if I have an env containing:

SASS_THEME="soft"

soft.scss : A SASS theme file containing something like:

$color-alpha: #e5e5e5;

main.scss : A main sass file looking something like:

// Import theme variables here
@import '${SASS_THEME}';

body{
    background: $color-alpha;
}
like image 628
Rogier Avatar asked Sep 20 '25 03:09

Rogier


1 Answers

You can use webpack aliases. It should be a path to the file with theme.

const env = require('./.env');
...
const theme = getThemeFromEnv(env); // you need to implement this method
...
resolve: {
 alias: {
  @SASS_THEME: theme
 }
}

and then use it in scss file:

// Import theme variables here
@import '@SASS_THEME';

body{
    background: $color-alpha;
}

UPD to load .env file use raw-loader:

rules: [
      {
        test: /\.env$/,
        use: 'raw-loader',
      },
],

it will load anything as raw string

UPD2
I've got it how to load .env with dotenv package

const dotenv = require('dotenv').config({path: __dirname + '/.env'});

console.log(dotenv.parsed) // output { SASS_THEME: 'soft' }

like image 89
nickbullock Avatar answered Sep 23 '25 10:09

nickbullock