无法加载样式表,因为MIME类型为text/html [英] Stylesheet not loading because MIME type is text/html
问题描述
在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
While running a MERN app on firefox, got this error in browser console and css is not loaded: The stylesheet http://localhost:3000/src/css/component.css was not loaded because its MIME type, "text/html", is not "text/css"
我正在像这样将CSS添加到index.html
:
I am adding CSS to index.html
like this :
<link rel="stylesheet" type="text/css" href="../src/css/component.css" />
我要去哪里错了?
除了React组件之外,还有哪些其他方法可以为部分添加外部CSS?
What are the other ways to add external css for sections apart from the React components ?
代码为此处
推荐答案
样式表 http://localhost:3000/src/css/component.css 不是 已加载,因为其MIME类型"text/html"不是"text/css"
The stylesheet http://localhost:3000/src/css/component.css was not loaded because its MIME type, "text/html", is not "text/css"
造成错误的原因是
当您在浏览器中提供公共目录时,您只能访问该公共目录,因此
you are allowed to access only public directory when its served on browser, so
->首先,通过../src/css/
您无法访问该文件,它将认为这是路由并尝试为您提供html
-> First ../src/css/
by this way you can't access the file , it will consider this as route and try to give you html
->其次,这不是包含CSS文件的正确方法:
-> Second , This is not the proper way to include css files :
<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 component js文件):
Proper way to use the css file is like this ( from your react component js file ) :
import './css/component.css';
(react-scripts start
)React将自动将您的CSS文件转换为js并应用它.
(react-scripts start
) React will automatically convert your css file into js and applies it.
如果您想在react之外使用css文件,则需要将所有css文件放在公用文件夹中(最好放在public/css里面)
Still if you want to use css files outside of react, you need to put all css files inside public folder (good to put inside 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" />
如果您仍然有疑问,请阅读:
If you still have doubts please read :
https://github.com/facebookincubator/create-react-app/blob/master/README.md#getting-started
希望,这将清除您的所有疑问.
Hope, this will clear all your doubts.
这篇关于无法加载样式表,因为MIME类型为text/html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!