拒绝应用样式,因为 MIME 类型

Tro*_*Leu 3 html css node.js reactjs webpack

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

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

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

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

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

由于 MIME 类型,未加载样式表

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

  <link rel="stylesheet" type="text/css" href="css/style.css"
Run Code Online (Sandbox Code Playgroud)

这是我的 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
        })
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我的项目目录结构:

  • 源文件

    • 成分

    • css

      • 样式文件
    • 索引.html
    • 索引.js

任何帮助,将不胜感激

Tro*_*Leu 5

所以事实证明我需要使用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
         })
    ]
}
Run Code Online (Sandbox Code Playgroud)