4

我在_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 所做的相同的事情。

4

5 回答 5

5

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

  1. 首先,尝试导入scss不带下划线的主文件,即代替../../styles/_colors.scss, try../../styles/index.scss或无论你的主文件是什么。

  2. 其次,跟踪变量名称。此代码不起作用:

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

而这个完美地工作

:export {
  textBlack: $text-black;
}

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

于 2020-01-19T03:36:31.487 回答
1

尝试重现这些步骤:

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;
于 2020-01-14T11:58:50.893 回答
0

如果您没有安装,请在项目中安装 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
于 2021-12-30T22:03:05.250 回答
0

如果您使用的是 CRA 版本 4,则存在一个已知问题,除非您将 scss 文件定义为 <name>.modules.css,否则此功能将不起作用。

有关详细信息,请参阅https://github.com/facebook/create-react-app/issues/10047#issuecomment-724227353

于 2021-11-17T06:03:59.283 回答
-1

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

于 2019-09-10T05:57:07.190 回答