【问题标题】:SASS: imported scss in index.js not rendering (using create-react-app)SASS:在 index.js 中导入的 scss 不呈现(使用 create-react-app)
【发布时间】:2025-12-12 15:00:01
【问题描述】:

我正在开发一个 create-react-app 项目,我使用以下说明将 SASS 连接到该项目:https://github.com/facebook/create-react-app

然后,在我的源代码中,我创建了一个样式文件夹,其中包含一个 partials 文件夹和一个 index.scss。在 partials 文件夹中,我有一个 firstComponent.scss 文件。我将第一个组件文件中的 scss 导入到我的 index.scss 中。样式已成功导入我的 index.css 文件。但是,它们不会在浏览器上呈现。为什么是这样?

这是我的 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './style/index.scss';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

这是我的 index.scss

@import './partials/_firstComponent';  

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

这是我的 firstComponent.scss

.firstComponent {
    background-color: 'red'; 
}

这是我的 index.css

.firstComponent {
  background-color: 'red'; }

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif; }

【问题讨论】:

  • 尝试使用import './style/index.css';而不是import './style/index.scss';
  • 你需要安装sass-loader并配置webpack来加载它。
  • 但我不想从 create-react-app 中弹出,并且我在 create-react-app github 上遵循的说明没有指定需要 sass-loader :/
  • 我尝试使用 import './style/index.css',但恐怕还是一样..
  • 哦!它突然起作用了..因为我将 import './style/index.scss' 更改为 './style/index.css' 我猜,但是为什么样式没有立即正确渲染?不过还是谢谢!!

标签: css reactjs sass


【解决方案1】:

你将需要这条线

require('./style/index.scss');

不是

导入'./style/index.scss';

【讨论】:

    最近更新 更多