【问题标题】:Using SCSS variables in CSS Modules在 CSS 模块中使用 SCSS 变量
【发布时间】:2017-04-07 09:33:25
【问题描述】:

我有一个_color.scss 文件,其中包含 400 种颜色作为变量。我喜欢 20 个组件,它们的样式中需要这种颜色变量。

我正在使用 SCSS + CSS 模块来构建我的样式。截至目前,我将这个_color.scss 导入到每个组件的style.scss 中。

例子:

component1.scss

@import "color.scss";

component2.scss

@import "color.scss";

component3.scss

@import "color.scss";

以前,当我单独使用 SCSS 时,我会将 color.scss 导入到我的 index.scss 并导入它下面的所有其他样式。这样,变量将在所有组件中可用。

例子:

//index.scss
@import "color.scss";
@import "component1.scss";
@import "component2.scss";
@import "component3.scss";

现在,_color.scss 下的所有变量都将在component1.scsscomponent2.scsscomponent3.scss 下可用。

有没有办法用CSS Modules + SCSS 做类似的事情?一个声明全局变量的地方?

【问题讨论】:

    标签: reactjs sass webpack css-modules react-css-modules


    【解决方案1】:

    我现在使用的方式看起来很干净。所以,我把它分享给大家。

    使用sass-resources-loader

    这将包括@import 到您的所有.scss 文件中,使变量和mixin 在使用css modules 时在所有scss 文件中可用。

    webpack@2.x.x 配置

    ...
        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, '../../')
            }
          })
         ]
    ...
    

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2020-08-22
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多