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

React中如何在JSX文件导入外部CSS?遇加载器报错求助

Fixing the CSS Import Error in Your React Webpack Project

Hey there, let's get this sorted out! The error you're seeing happens because your Webpack config isn't set up correctly to process your custom CSS file. Let's break down the issues and fix them step by step:

1. Missing CSS Loaders

Webpack doesn't know how to handle CSS files out of the box—you need to tell it to use style-loader and css-loader to parse and inject the styles into your app. Right now your config doesn't specify these loaders at all, which is why you're getting the "appropriate loader" error.

2. Incorrect Include Path

Your current config only tells Webpack to process CSS files inside /node_modules/, but your Login.css is in the root path. That means Webpack is ignoring your custom CSS file entirely.


Step 1: Install Required Loaders

First, install the two loaders we need via npm (or yarn):

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

Step 2: Update Your Webpack Config

Replace your existing module section with this updated code. I'll explain the changes below:

var config = {
  entry: './main.js',
  output: {
    path: '/',
    filename: 'index.js',
  },
  devServer: {
    inline: true,
    port: 8080
  },
  module: {
    // Note: Webpack 2+ uses `rules` instead of `loaders` (though `loaders` still works for backwards compatibility)
    rules: [
      {
        test: /\.css$/,
        // Remove the `include: /node_modules/` line—we want to process ALL .css files, including your root-level Login.css
        // If you later need to exclude certain paths, you can add `exclude: /some-folder/` instead
        use: [
          'style-loader', // Injects the processed CSS into the DOM as <style> tags
          'css-loader'    // Parses CSS files and resolves imports/urls
        ]
      }
    ]
  }
};

Step 3: Verify and Restart

  • Double-check that Login.css is indeed in your project root (same level as main.js and your Webpack config file).
  • Make sure your import statement is still import "./Login.css" in your React component.
  • Restart your Webpack dev server—this is crucial for config changes to take effect!

After these steps, your CSS should load correctly, and the .Login class will apply the padding style to your component.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:17:20