迁移AngularJS项目至Webpack遇报错:无法解析'./style.css'
Hey there, let's break down why you're running into this CSS file error when migrating from Gulp to Webpack. The key thing to know is: Webpack only understands JavaScript by default — it has no clue how to handle CSS files unless you tell it exactly what to do with them. That "Module not found" message is a bit misleading here; it's less about Webpack not locating your style.css file (assuming it's actually in the same /src/js folder as your index.js) and more about it lacking the tools to process the CSS.
Here's how to fix it step by step:
Install the required loaders
You need two packages to handle CSS in Webpack:css-loader: Parses the CSS file and resolves any imports/urls inside itstyle-loader: Takes the parsed CSS and injects it into the browser's DOM as a<style>tag
Run this command in your project root to install them as dev dependencies:
npm install --save-dev css-loader style-loader # Or if you use Yarn: # yarn add -D css-loader style-loaderUpdate your Webpack config
Open yourwebpack.config.jsfile and add amodule.rulessection to tell Webpack how to process.cssfiles. Here's what that should look like:module.exports = { // Your existing config entries (entry, output, devServer, etc.) go here module: { rules: [ { // Match any .css file test: /\.css$/, // Use these loaders (order matters: right to left execution) use: ['style-loader', 'css-loader'] } ] } };Quick note: The order of loaders in the
usearray is important. Webpack runs them from right to left, socss-loaderprocesses the file first, thenstyle-loaderhandles injecting it into the page.Double-check your file path
Just to be safe, confirm thatstyle.cssis actually located in/Users/username/Development/yd-front-end/src/js(the folder Webpack is looking in). If it's in a different location (like/srcinstead of/src/js), adjust your import path inindex.jsto match, e.g.:import '../style.css';
Once you've done these steps, restart your Webpack dev server, and the error should be gone!
内容的提问来源于stack exchange,提问作者Edgar Quintero

