【问题标题】:Stylesheet not loading because MIME type is text/html样式表未加载,因为 MIME 类型为 text/html
【发布时间】:2018-04-19 11:23:37
【问题描述】:

在 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”

我正在向index.html 添加 CSS,如下所示:

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

我哪里错了?

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

代码是Here

【问题讨论】:

  • 能否分享一下文件夹结构和component.css文件在哪里?
  • 代码在这里:https://gitlab.com/menkudle/MERN-CommentBox

标签: javascript css node.js reactjs mime-types


【解决方案1】:

样式表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

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

【讨论】:

  • import './css/component.css' 添加到 index.js,除了我们正在渲染的特定 React 组件之外,该 css 是否会应用于整个页面
  • 这解决了 Angular 的问题。我尝试链接 CSS,而不是让组件将其引入。从 index.html 中删除链接解决了问题。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    来自

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

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

    //correct way should be like this
    
    new MiniCssExtractPlugin({
      publicPath: './sass/',
      filename: './style.[contenthash].css'
    });

    希望对您有所帮助。

    【讨论】:

      【解决方案4】:

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

      &lt;link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/css/component.css" /&gt;

      它对我有用..

      还有更好的方法吗??

      【讨论】:

        猜你喜欢
        • 2020-06-22
        • 2018-07-08
        • 2011-01-12
        • 2017-09-17
        • 2021-12-29
        • 2018-11-25
        • 2020-11-10
        • 2020-11-03
        相关资源
        最近更新 更多