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

*爱你&永不变心* 提交于 2019-12-24 18:31:47

问题


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;
}

回答1:


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' }



来源:https://stackoverflow.com/questions/59086681/sass-conditional-imports-based-on-env-variables-using-webpack-to-use-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!