You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

webpack-dev-server加载CSS报错:无法解析main.css,如何解决?

Fixing "Can't resolve 'main.css'" Error with Webpack + style-loader/css-loader

Hey there, let's work through this "Module not found" error—it's one of the most common hiccups when setting up CSS loading in Webpack, and we can fix it with a few quick checks:

1. Double-check your file path & import statement

First, make sure your main.css is actually located where you're telling Webpack to look. If your index2.js is in src/, your CSS file needs to be in the same src/ directory, and your import should include the relative path prefix (./):

// Correct import (looks in the same directory as index2.js)
import './main.css';

// Wrong import (Webpack will search node_modules instead)
import 'main.css';

If your CSS is in a subfolder like src/styles/main.css, update the import to match:

import './styles/main.css';

2. Verify your Webpack configuration

Ensure your webpack.config.js has the correct loader setup for CSS files. The order of loaders matters here—Webpack processes them from right to left, so css-loader comes first (parses the CSS) followed by style-loader (injects it into the DOM):

module.exports = {
  // ... other config options (entry, output, etc.)
  module: {
    rules: [
      {
        test: /\.css$/i, // Matches all .css files
        use: ['style-loader', 'css-loader'], // Order is critical!
      },
    ],
  },
};

3. Confirm you've installed the required loaders

It's easy to forget this step—make sure you've added style-loader and css-loader as dev dependencies:

npm install style-loader css-loader --save-dev

Check your package.json to confirm they're listed under devDependencies before restarting your dev server.

4. Clear Webpack cache & restart the dev server

Sometimes cached build data can cause false "missing file" errors. Stop your webpack-dev-server instance, delete any cached files (look for a node_modules/.cache folder or a dist folder if you have one), then restart the server with your usual command (like npm start or npx webpack serve).


内容的提问来源于stack exchange,提问作者Magnus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:51:01