Webpack开发环境执行npm run start-dev时CSS未加载的问题解决咨询
Hey there! Let's walk through fixing that CSS not loading issue you're facing with your Webpack dev server. Looking at your code, here are the most likely fixes to get things working:
1. Install the required CSS loaders first
Webpack relies on style-loader and css-loader to process and inject CSS into your project, but it’s easy to forget installing them. Run this command in your project root to add them as dev dependencies:
npm install --save-dev style-loader css-loader
2. Switch Webpack mode to development for dev server
Your current config uses mode: "production"—while this works for building production-ready bundles, the dev server functions best with development mode. Production optimizations can sometimes interfere with live CSS loading, so update your webpack.config.js:
const path = require("path"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js" }, mode: "development", // Update this line module: { rules: [ { test: /\.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" } ] } ] }, // Optional: Add dev server config for better dev experience devServer: { static: path.resolve(__dirname, "dist"), hot: true, // Enable hot module replacement for faster updates open: true // Auto-open browser when server starts } }
3. Check your start-dev script in package.json
Make sure your npm script is actually launching the Webpack dev server, not just building the bundle. Your package.json should have a script like this:
{ "scripts": { "start-dev": "webpack serve --config webpack.config.js" } }
Using webpack serve is key here—if you were just running webpack, it would only compile the bundle without starting the live server.
4. Verify your CSS file path is correct
In your index.js, you’re importing ./style/style.css. Double-check your project structure matches this path:
your-project/ ├── src/ │ ├── index.js │ └── style/ │ └── style.css ├── webpack.config.js └── package.json
If your CSS file is in a different location, adjust the import path to match.
After making these changes, stop any running dev server and restart it with npm run start-dev—your CSS should load properly now!
内容的提问来源于stack exchange,提问作者Rizal Maulana

