Using SCSS variables in CSS Modules

风格不统一 提交于 2021-02-18 22:33:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!