React中如何在JSX文件导入外部CSS?遇加载器报错求助
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.cssis indeed in your project root (same level asmain.jsand 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

