[英]Use sass variables into js files create-react-app
我在_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 所做的相同的事情。
我遇到了类似的问题,我花了很多时间才得到想要的结果。 如果您已经安装了node-sass
,请尝试以下操作。
首先,尝试导入不带下划线的主scss
文件,即代替../../styles/_colors.scss
,尝试../../styles/index.scss
或您的主文件是什么。
其次,跟踪变量名称。 此代码不起作用:
:export {
$textBlack: $text-black;
}
虽然这个完美地工作
:export {
textBlack: $text-black;
}
出于某种原因,它不喜欢变量名中的美元符号,尽管它是一个有效的 JS 变量名。 你的情况应该可以正常工作
尝试重现这些步骤:
npm i --save-dev node-sass
example.scss
。$hello: 'world';
:export {
my-var: $hello;
}
import React from 'react';
import Example from './example.scss';
export default () => Example.hello;
如果您使用的是 CRA 版本 4,则存在一个已知问题,即除非您将 scss 文件定义为 <name>.modules.css,否则此功能将无法使用。
有关详细信息,请参阅https://github.com/facebook/create-react-app/issues/10047#issuecomment-724227353 。
如果您没有安装 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
为了在 CRA 中加载 SCSS 文件,您需要将node-sass
添加为 package.json 的依赖项。 我已经对其进行了测试,并将其添加到 clean CRA 项目并导入colors
对象(使用:export
,就像您提供的代码中一样)按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.