reactjs - 在 CSS 模块中使用 SCSS 变量

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

我有一个 _color.scss 文件,其中包含 400 种颜色作为变量。我有 20 个组件在其样式中需要此颜色变量。

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

示例:

组件1.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 模块 + SCSS 执行类似的操作?在一个地方声明全局变量?

最佳答案

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

使用sass-resources-loader

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

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

关于reactjs - 在 CSS 模块中使用 SCSS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40763372/

相关文章:

javascript - 从数组中删除项目,重新排序项目,然后放回去(reactjs)

typescript - webpack UMD : Critical dependency. ..无法静态解压

javascript - ValidationError : Invalid options object. 开发中间件已使用与 API 架构不匹配的选项对象进行初始化

reactjs - typescript + VS 代码 : Cannot find module "myimage.png"

node.js - react : how to load image outside src and public folders

css - FIxedDataTable CSS 解析错误

mysql - 如何处理通过 url 发送的问号?

css - 断行代码有很多 :not in scss

Angular CLI SASS 选项

css - PrimeNg 展开容器的行全宽