Webpack css-loader 不处理 css 尽管配置看起来没问题

Webpack css-loader not handling the css although the configuration appears to be alright

我现在正在学习 webpack,我无法弄清楚这一点。我真的很感激一些帮助。 我收到此错误:

ERROR in ./src/style.css 1:5
Module parse failed: Unexpected token (1:5)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> body {
|     background-color: red;
|     color: white;
 @ ./src/index.js 1:0-20

我已经导入了 css-loader 和 style-loader:npm i -D css-loader style-loader。 package.json 文件如下所示:

  {
  "name": "webpack-styles",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^5.2.6",
    "style-loader": "^3.0.0",
    "webpack": "^5.42.0",
    "webpack-cli": "^4.7.2"
  }
}

webpack.config.js 看起来像这样:

module.exports = {
    module: {
      rules: [
        {
          test: /\.css$/i,
          use: [ "css-loader", "style-loader"],
        },
      ],
    },
  };

并且我已经将 css 文件导入到 index.js 中,如下所示:

import "./style.css"

谁能看出问题出在哪里? 谢谢!

尝试将您的 webpack.config.js 替换为:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

注意顺序:

  1. style-loader
  2. css-loader

配置是顺序敏感的,在webpack文档中是这样的: https://webpack.js.org/loaders/style-loader/#root