问题
I've a _color.scss
file which consists of 400 colors as variables. And I've like 20 components which needs this color variables in their styles.
I'm using SCSS + CSS Modules to construct my styles. As of now, I'm importing this _color.scss
in each and every component's style.scss
.
Example:
component1.scss
@import "color.scss";
component2.scss
@import "color.scss";
component3.scss
@import "color.scss";
Previously, when I was using SCSS standalone, I'll import the color.scss
to my index.scss
and import all the other styles below it. By this, the variables will be available across all the components.
Example:
//index.scss
@import "color.scss";
@import "component1.scss";
@import "component2.scss";
@import "component3.scss";
Now, all the variables under _color.scss
will be available under component1.scss
, component2.scss
and component3.scss
.
Is there a way to do something similar to this with CSS Modules + SCSS
? A single place to declare global varibales?
回答1:
The way I'm using now looks pretty clean. So, I'm sharing it to all.
Use sass-resources-loader
This will include the @import
to all your .scss
files making the variables and mixins available across all the scss
files while using css modules
.
The webpack@2.x.x config
...
module: {
rules: [
{
test: /\.scss$/,
loaders: [
'style-loader',
'css-loader?modules&importLoaders=1&localIdentName=[path][name]__[local]__[hash:base64:10]',
'sass-loader',
'sass-resources-loader',
'import-glob-loader',
'postcss-loader',
],
},
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer(),
],
sassResources: [
'./app/constants/_style-variables.scss', //include your scss imports here
],
context: path.resolve(__dirname, '../../')
}
})
]
...
来源:https://stackoverflow.com/questions/40763372/using-scss-variables-in-css-modules