问题
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