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

React应用导入CSS样式失败,报Module parse failed错误求助

Fixing the CSS Module Parse Error in Your React App

Hey there, let's get that CSS loading issue sorted out! The error you're seeing means Webpack doesn't have the necessary tools to process your CSS files—by default, it only knows how to handle JavaScript and JSON. Here's exactly what you need to do:

Step 1: Install the Required Loaders

First, you'll need two packages to tell Webpack how to parse and inject CSS into your app: style-loader and css-loader. Run this command in your project root:

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

If you use Yarn, replace npm install with yarn add --dev.

Step 2: Update Your Webpack Configuration

Open your webpack.config.js file (if you're using a custom Webpack setup) and add a new rule to the module.rules array. This tells Webpack to use the loaders for any .css files:

module.exports = {
  // ... other Webpack config settings
  module: {
    rules: [
      // Keep your existing rules (like babel-loader for JSX/JS)
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
        // Optional: Restrict to your styles directory to speed up processing
        // include: path.resolve(__dirname, 'src/styles')
      },
    ],
  },
};

Quick breakdown of what each loader does:

  • css-loader: Parses the CSS file and resolves any imports/url() references inside it.
  • style-loader: Takes the parsed CSS and injects it into the DOM as a <style> tag so your styles take effect.

If You're Using Create React App

If you started your project with Create React App (CRA), it should already support CSS imports out of the box. If you're still getting this error, double-check:

  • Your import statement is correct: import './styles/styles.css'; (make sure the file path matches where your CSS is stored relative to your component).
  • You haven't ejected your CRA setup and accidentally removed the CSS loader config. If you did eject, follow Step 2 above to re-add the rule.

Final Check

After making these changes, restart your development server (npm start or yarn start)—the error should be gone, and your red text styles should show up!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:08:59