【问题标题】:Use sass variables into js files create-react-app在 js 文件中使用 sass 变量 create-react-app
【发布时间】:2022-03-29 20:52:07
【问题描述】:

我在_colors.scss 文件中有一些颜色定义的变量。

$color-succcess: #706caa;
$color-error: #dc3545;

我还想将它们用于一些样式化的反应组件react-table 到我的 js 文件中。

我使用以下文章 https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript 作为参考,许多其他人都喜欢它,但我无法让它工作。

我从我的 scss 文件中导出颜色:

:export {
  colorSuccess: $color-succcess;
  colorError: $color-error;
}

然后我将它们导入到我的 js 文件中:

import colors from "../../styles/_colors.scss";

但它们可能没有正确加载。

如何配置 create-react-app 生成的代码以实现与本文中的人使用 webpack 所做的相同的事情。

【问题讨论】:

标签: javascript reactjs sass create-react-app icss


【解决方案1】:

我也遇到过类似的问题,我尝试了很多次才得到想要的结果。如果您已经安装了node-sass,请尝试以下操作。

    1234563
  1. 其次,跟踪变量名称。此代码无效:

:export {
  $textBlack: $text-black;
}

虽然这个完美运行

:export {
  textBlack: $text-black;
}

由于某种原因,它不喜欢变量名中的美元符号,尽管它是一个有效的 JS 变量名。您的情况应该可以正常工作

【讨论】:

    【解决方案2】:

    尝试重现这些步骤:

    1。通过安装 node-sass 在 CRA 中启用 sass。

    npm i --save-dev node-sass
    

    2。创建一个 sass 文件example.scss

    $hello: 'world';
    
    :export {
      my-var: $hello;
    }
    

    3。将 sass 导入你的 react 组件。

    import React from 'react';
    import Example from './example.scss';
    
    export default () => Example.hello;
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 CRA 版本 4,则存在一个已知问题,除非您将 scss 文件定义为 .modules.css。

      详情请见https://github.com/facebook/create-react-app/issues/10047#issuecomment-724227353

      【讨论】:

        【解决方案4】:

        如果您没有安装 sass,请在项目中安装它。

        yarn add --dev node-sass
        

        创建一个文件并使用此规则命名它 => filename.module.scss(例如 variables.module.scss )

        $color-succcess: #706caa;
        $color-error: #dc3545;
        
        :export {
          colorSuccess: $color-succcess;
          colorError: $color-error;
          otherColor: #786539;
        } 
        

        并将其导入到组件中,如下所示:

        import colors from "../../styles/_colors.module.scss";
        
        const TheComponent = () => {
           console.log(colors.colorSuccess)
        
           return <h1>The Component</h1>
        }
        
        export default TheComponent
        
        // output in console : #706caa
        

        【讨论】:

          【解决方案5】:

          为了在 CRA 中加载 SCSS 文件,您需要添加 node-sass 作为 package.json 的依赖项。我已经对其进行了测试,在将其添加到清理 CRA 项目并导入 colors 对象(使用 :export,就像您提供的代码中一样)后按预期工作。

          【讨论】:

          • 默认情况下这不起作用。也许需要额外的配置?
          猜你喜欢
          • 2019-10-14
          • 2019-04-06
          • 1970-01-01
          • 2020-08-17
          • 2019-04-07
          • 1970-01-01
          • 2018-09-16
          • 2020-04-25
          • 1970-01-01
          相关资源
          最近更新 更多