Webpack配置:如何通过CSS加载器指定CSS文件路径?
Let's break down what's happening here and get your CSS imports working smoothly.
The Core Problem
Your current include setting in the CSS loader rule only tells Webpack which CSS files to process with these loaders — it doesn't make Webpack automatically search the src/styles directory when you write import 'style.css'. By default, Webpack looks for imported files in the current directory (src/) and node_modules, which is why it can't locate your style.css in src/styles/.
Solution 1: Use resolve.alias for Clean, Shorthand Imports
Set up an alias for your styles directory to make imports more intuitive. Update your webpack.config.js like this:
const path = require('path'); module.exports = { // ... your existing config options resolve: { alias: { // Create an alias "@styles" that maps directly to your styles folder '@styles': path.resolve(__dirname, 'src/styles/') } }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], include: [path.resolve(__dirname, 'src/styles/')] // Keep this to limit loader processing to your target folder } ] } };
Then in your index.js, import the CSS using the alias:
import '@styles/style.css';
Solution 2: Add src/styles to Webpack's Module Search Paths
If you want to keep your original import 'style.css' syntax, add the src/styles directory to Webpack's module search list. This tells Webpack to check this folder when resolving imports:
const path = require('path'); module.exports = { // ... your existing config options resolve: { modules: [ path.resolve(__dirname, 'src/styles'), // Add your styles directory first in the search order 'node_modules' // Keep node_modules as a fallback for third-party packages ] }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], include: [path.resolve(__dirname, 'src/styles/')] } ] } };
Now your original import 'style.css' will work exactly as you want.
Quick Alternative: Use a Relative Path
If you don't want to tweak your Webpack resolve config, you can use a relative path in your import:
import './styles/style.css';
Just confirm the path is correct — since index.js lives in src/, ./styles/ points directly to src/styles/.
Double-Check Dependencies
Before building, make sure you've installed the required loaders:
npm install --save-dev style-loader css-loader
内容的提问来源于stack exchange,提问作者Madhura KM

