i have this sass directory:
- _vars.scss
- main.scss
//vars.scss
$base-container: 1400px;
//main.scss
Webpack 4 solution:
{
loader: 'sass-loader', options: {
sourceMap: true,
prependData: '@import "pathto/vars";'
},
}
In order @import "pathto/vars";
to work you need Webpack to configure to resolve such imports. So it simply prepends the line.
This solution is good because you have no issues with sourcemaps like with using sass-resources-loader
If you have Webpack 5 you have to use additionalData, the other options are not valid now:
{
loader: 'sass-loader',
options: {
additionalData: '@import path/to/general.sass',
}
},
If you do like this your general sass or scss file will get prepended
You have to import the vars
file into every Sass partial that uses those variables, because every partial is compiled on its own; none of the files will 'know about' the others unless you specifically import them.
If you don't want to have to type the import
s in every Sass file, you can look at baggage-loader, which will automatically add them for you.
Without using sass-resources-loader:
Thanks to @Arseniy-II for helping me get to this answer, in conjunction with this thread: https://github.com/webpack-contrib/sass-loader/issues/218
Using loader options in your webpack module rules, you can assign a data property to sass-loader, you should then be able to use all sass functions as expected:
module: {
rules: [
// Apply loader
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
data: '@import "path/to/global.scss";',
includePaths:[__dirname, 'src']
},
},
],
},
],
}
https://github.com/shakacode/sass-resources-loader
sass-resources-loader allow to use variables, mixins etc in each required sass file.
So you can have your variables in vars.scss:
$main: #073288;
$secondary: #F6A906;
And then use them as usual:
.my-component {
background-color: $main;
color: $secondary;
}
Install sass-resources-loader:
npm install sass-resources-loader --save-dev
And configure you webpack.config:
{
loader: 'sass-resources-loader',
options: {
resources: './path/to/vars.scss'
}
}
module: {
rules: [
// Apply loader
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader',
{
loader: 'sass-resources-loader',
options: {
resources: ['./path/to/vars.scss', './path/to/mixins.scss']
},
},
],
},
],
}
If you have problems with path to resources try to use path like this:
const path = require('path')
resources: [path.resolve(__dirname, './../vars.scss')]
__dirname
is avaliable inside you webpack.config without requiring it.