【问题标题】:Refusing to apply styles because MIME type拒绝应用样式,因为 MIME 类型
【发布时间】:2018-12-19 01:08:18
【问题描述】:

我正在开发一个在 npm 的 webpack-dev-server 上运行的 React 应用程序。运行服务器后,我注意到在浏览器控制台中收到以下消息:

“拒绝应用来自 'http://localhost:8080/css/index.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。” p>

除了标题为 style.css 的自定义 css 文件之外,我能够获取以下所有资源。当我直接从包含文件夹运行应用程序(不在本地服务器上运行)时,style.css 文件加载没有问题。

我需要在 webpack 中使用 css 加载器吗?

我已经查看了以下帖子并尝试了所有建议,但无济于事:

Stylesheet not loaded because of MIME-type

在 index.html 中,我使用了如下格式的链接标签:

  <link rel="stylesheet" type="text/css" href="css/style.css"

这是我的 webpack.config.js 文件:

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            }
        ]
    },
    plugins: [
        new HTMLWebpackPlugin({
        template: './src/index.html', //source
        filename: 'index.html'  //destination
        })
    ]
}

这是我的项目目录结构:

  • src

    • 组件

    • css

      • style.css
    • index.html
    • index.js

任何帮助将不胜感激

【问题讨论】:

  • 您在 webpack.config.js 中使用 css 或样式加载器吗? stackoverflow.com/questions/48248832/… 的可能重复项
  • 目前我只使用普通的 css 文件。还没有 css 加载器,因为我没有直接将 css 样式导入到我的组件中
  • 您看过并尝试过我提供的链接吗? ?如果没有解决,那一定是因为没有使用样式和 CSS 加载器!
  • 我有一种预感,Subanshu 是正确的。请求 CSS 文件时得到的响应是什么?您可以在开发者控制台的“网络”选项卡下看到此内容并选择文件的预览。可能是 Webpack 开发服务器产生的 404 响应。

标签: html css node.js reactjs webpack


【解决方案1】:

所以我需要使用 style-loader 和 css-loader。我怀疑问题完全在于 webpack-dev-server 以及它是如何引用样式表的。我正在使用 webpack 4,以防它在未来对任何人有所帮助。

我的 webpack.config.js 现在看起来像这样:

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    },
    plugins: [
         //will automatically inject bundle js into ./dist/index.html
         new HTMLWebpackPlugin({
             template: './src/index.html', //source
             filename: 'index.html'  //destination
         })
    ]
}

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 2018-11-25
    • 2020-07-14
    • 2018-07-24
    • 2019-11-20
    • 2020-11-10
    • 2018-08-22
    • 2018-10-24
    相关资源
    最近更新 更多