在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
没有加载样式表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并应用它。
如果你想在反应之外使用css文件,你需要将所有css文件放在公共文件夹中(很好放在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
希望,这将清除你所有的疑虑。
我使用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移动到公共目录并将component.css
引用为
<link rel="stylesheet" type="text/css" href="%PUBLIC_URL%/css/component.css" />
它对我有用..
有更好的方法??
您必须检查服务器上是否存在该文件。我找到了原因,因为在将源代码上传到服务器时没有文件(或丢失)。因此,当找不到css文件时,服务器返回html MIME类型