Sass Vars Loader
Use external vars in your SCSS files
This loader allows you to load Sass variables from:
- JSON files
- Javascript files
- Inlined in your Webpack config file
Install
using npm
npm install @epegzz/sass-vars-loader --save-dev
using yarn
yarn add @epegzz/sass-vars-loader --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: {
syntax: 'scss',
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: {
syntax: 'scss',
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 = {
blueFromJavascript: '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: {
syntax: 'scss',
files: [
path.resolve(__dirname, 'config/sassVars.js')
]
}
}]
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
Pro Tip: Nested Vars!
Use map_get
in order to use objects as Sass vars:
module.exports = {
lightTheme: {
background: 'white',
color: 'black'
},
darkTheme: {
background: 'black',
color: 'gray'
}
};
$theme: $lightTheme;
.some-class {
background: map_get($theme, background);
color: map_get($theme, color);
}