样式表未加载,因为 MIME 类型为 text/html

IT技术 javascript css node.js reactjs mime-types
2021-05-25 13:30:15

在 firefox 上运行 MERN 应用程序时,在浏览器控制台中出现此错误并且未加载 css: The stylesheet http://localhost:3000/src/css/component.css was not loaded because its MIME type, “text/html”, is not “text/css”

我正在添加 CSSindex.html像这样:

 <link rel="stylesheet" type="text/css" href="../src/css/component.css" />

我哪里错了?

除了 React 组件之外,还有哪些其他方法可以为部分添加外部 css?

代码在 这里

4个回答

样式表http://localhost:3000/src/css/component.css未加载,因为其 MIME 类型“text/html”不是“text/css”

错误的原因是,

当它在浏览器上提供时,你只能访问公共目录,所以

-> 首先../src/css/通过这种方式您无法访问该文件,它会将其视为路由并尝试为您提供 html

-> 其次,这不是包含 css 文件的正确方法:

<link rel="stylesheet" type="text/css" href="../src/css/normalize.css" />
<link rel="stylesheet" type="text/css" href="../src/css/demo.css" />
<link rel="stylesheet" type="text/css" href="../src/css/component.css" />

使用 css 文件的正确方法是这样的(来自您的react组件 js 文件):

import './css/component.css';

( react-scripts start) React 会自动将你的 css 文件转换成 js 并应用它。


如果你想在 react 之外使用 css 文件,你需要把所有的 css 文件放在 public 文件夹中(最好放在 public/css 中)

<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" />

如果您仍有疑问,请阅读:

https://github.com/facebookincubator/create-react-app/blob/master/README.md#getting-started

希望,这将消除您的所有疑虑。

您必须检查服务器上是否存在该文件。我找到了原因,因为上传源代码到服务器时没有文件(或丢失)。所以当找不到 css 文件时,服务器返回 html MIME 类型

我正在使用 MiniCssExtractPlugin 并且我意识到缺少 ' . ' 将导致以下问题。

filename: '/style.[contenthash].css'

filename: './style.[contenthash].css'

//correct way should be like this

new MiniCssExtractPlugin({
  publicPath: './sass/',
  filename: './style.[contenthash].css'
});

希望这对你有帮助。

我将文件夹 css 和 js 移动到 public 目录并引用component.cssas

<link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/css/component.css" />

它对我有用..

任何更好的方法?