Search code examples
webpackcss-loader

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


I am learning webpack at moment and I can't figure this one out. I would really appreaciate some help. I am getting this error:

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

I have imported both css-loader and style-loader with: npm i -D css-loader style-loader. The package.json file looks like this:

  {
  "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 looks like this:

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

and I have imported the css file into the index.js like this:

import "./style.css"

Can anyone see what the issue might be? Thank you!


Solution

  • Try replacing your webpack.config.js with:

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

    Note the order:

    1. style-loader first
    2. css-loader second

    the configuration is order sensitive, and it's exactly like this in webpack documentation: https://webpack.js.org/loaders/style-loader/#root