How to use global variables in CSS-Modules?

点点圈 提交于 2020-01-02 02:39:06

问题


I'm busy learning React with CSS-Modules and I don't quite understand how one would store variables? For example, in Sass you're able to do this:

// _variables.scss
$primary-color: #f1f1f1; 

// heading.scss
@import './variables';
.heading {
  color: $primary-color
}

How do you achieve this in CSS Modules?


回答1:


One way could be to use dependencies. For example,

// variables.css
.primaryColor {
  color: #f1f1f1
}

// heading.css
.heading {
  composes: primaryColor from "./variables.css"
}

See more detailed information here: https://github.com/css-modules/css-modules#dependencies

If you're using webpack there are more examples here: https://github.com/webpack/css-loader#composing-css-classes

Also if you are using webpack you can still use Sass with CSS modules.




回答2:


The CSS-Modules documentation mentions variables here: https://github.com/css-modules/css-modules/blob/master/docs/values-variables.md

With this you can import variables as so:

@value colors: "../../main/colors.css";
@value primary, secondary, tertiary from colors;

which can be used in your css:

.main {
    background-color: tertiary;
    border-top: 30px solid primary;
}

To make this work postcss-loader and postcss-modules-values need to be added to your webpack config. See below:

        {
            test: /\.css$/,
            use: [{
                    loader: 'style-loader'
                },
                {
                    loader: 'css-loader',
                    options: {
                        modules: true,
                        localIdentName: '[name]_[local]_[hash:base64:5]'
                    }
                },
                {
                    loader: 'postcss-loader',
                    options: {
                        plugins: [postcssModulesValues]
                    }
                }
            ]
        }



回答3:


Check this out

//vars.css
:root {
  --color-black: #222;
}


//myComponent.module.css
@import './vars.css';

.component{
  color: var(--color-black);
}



回答4:


You may use sass preprocessor and sass-resources-loader.

sass-resources-loader will add all your variables, mixins, etc into each required sass file.



来源:https://stackoverflow.com/questions/40779623/how-to-use-global-variables-in-css-modules

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