Sass Vars Loader
Use vars in your SCSS files provided via Webpack
This loader allows you to load Sass variables from:
- JSON files
- Javascript files
- Inlined in your Webpack config file
Install
npm install @epegzz/sass-vars-loader --save-dev
Usage
Look at the Example Webpack Config File to see how to use this
loader in conjunction with style-loader and
css-loader
Option 1: Inline Sass vars in the webpack config
.some-class {
background: $greenFromWebpackConfig;
}
var path = require('path');
module.exports = {
entry: './src/index.js',
module: {
rules: [{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader", options: { includePaths: ["app/styles.scss"] } },
{ loader: "@epegzz/sass-vars-loader", options: {
vars: {
greenFromWebpackConfig: '#0f0'
}
}
}]
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Option 2: Load Sass vars from JSON file
{
"purpleFromJSON": "purple"
}
.some-class {
background: $purpleFromJSON;
}
var path = require('path');
module.exports = {
entry: './src/index.js',
module: {
rules: [{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader", options: { includePaths: ["app/styles.scss"] } },
{ loader: "@epegzz/sass-vars-loader", options: {
files: [
path.resolve(__dirname, 'config/sassVars.json')
]
}
}]
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Option 3: Load Sass vars from Javascript file
module.exports = {
blueFromJS: 'blue'
};
.some-class {
background: $blueFromJavascript;
}
var path = require('path');
module.exports = {
entry: './src/index.js',
module: {
rules: [{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader", options: { includePaths: ["app/styles.scss"] } },
{ loader: "@epegzz/sass-vars-loader", options: {
files: [
path.resolve(__dirname, 'config/sassVars.js')
]
}
}]
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Pro Tipp: Nested Vars!
Use map_get
in order to use objects as Sass vars:
module.exports = {
lightTheme: {
background: 'white'
}
};
.some-class {
background: map_get($lightTheme, background);
}
Acknowledgments
Sass var generator shamelessly copied from Kasu/jsonToSassVars.js