Webpack@4.0.0:已配置css-loader和style-loader仍出现模块解析失败错误
Hey, I’ve run into this exact issue before with Webpack 4—those "Unexpected token" errors for CSS files usually boil down to a tiny misconfiguration in your Webpack setup, even if you have css-loader and style-loader installed. Let’s break down the most likely fixes:
1. Double-Check Your Webpack Config Rules
The #1 culprit here is that your webpack.config.js isn’t telling Webpack to use those loaders for CSS files. You need a clear rule targeting .css files, and loader order matters (Webpack processes them right-to-left). Here’s what the correct rule should look like:
module.exports = { // Your existing entry/output config here... module: { rules: [ { test: /\.css$/, // Matches all .css files in your project use: ['style-loader', 'css-loader'] // style-loader runs last, css-loader first } ] } };
Make sure you check these details:
- The
testregex is exactly/\.css$/—no typos like missing the dot or incorrect slashes. - You didn’t reverse the loaders. If you put
css-loaderfirst, Webpack will try to run it afterstyle-loader, which breaks the parsing flow entirely.
2. Install Webpack 4-Compatible Loader Versions
Webpack 4 doesn’t play nicely with the latest versions of css-loader and style-loader (those are built for Webpack 5+). If you installed the latest versions by accident, that’s probably causing the issue. Reinstall compatible versions with this command:
npm install css-loader@4.x style-loader@1.x --save-dev
3. Verify Your CSS Import Paths
Double-check the paths you’re using to import CSS in entry.js. For example, if your entry file is in the root directory, importing ./src/css/autosuggest-style.css is correct—but if you forgot the leading ./ (like src/css/autosuggest-style.css), Webpack might not resolve the file properly, leading to parsing errors.
If none of these fixes work, share your full webpack.config.js and package.json files. Common hidden issues include typos in loader names, missing the entire module block in your config, or conflicting rules that override your CSS loader setup.
内容的提问来源于stack exchange,提问作者Imran

