Webpack编译报错:ERROR in Must have a source file to refactor 求助
I’ve helped several developers troubleshoot this exact error with the @ngtools/webpack plugin, and it almost always boils down to missing critical Angular project context in your Webpack configuration. Let’s break down why this happens and how to fix it:
Why the error occurs
The @ngtools/webpack plugin isn’t just a simple TypeScript loader—it needs to connect to your Angular project’s metadata (like your tsconfig.json and entry files) to properly process your .ts files. When you only specify { test: /\.ts$/, use: '@ngtools/webpack' } without additional setup, the plugin can’t locate the source files it needs to refactor during compilation, hence the error thrown from ./node_modules/@ngtools/refactor.js.
Step-by-step fixes
1. Add the AngularCompilerPlugin to your Webpack config
You need to explicitly initialize the AngularCompilerPlugin to give the loader the context it needs. Here’s how to update your config:
const { AngularCompilerPlugin } = require('@ngtools/webpack'); module.exports = { // Other Webpack config (entry, output, etc.) module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, // Exclude node_modules to avoid processing external TS files use: '@ngtools/webpack', }, ], }, plugins: [ new AngularCompilerPlugin({ tsConfigPath: './tsconfig.json', // Path to your project's tsconfig mainPath: './src/main.ts', // Path to your Angular app's entry file sourceMap: true, // Optional: Enable if you need source maps }), ], };
This plugin tells @ngtools/webpack exactly where to find your project’s source files and compilation settings.
2. Verify your tsconfig.json includes all source files
Make sure your tsconfig.json has a correct include array to cover all your Angular source files:
{ "compilerOptions": { // Your existing compiler options }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] }
If the include range is too narrow, the plugin won’t be able to locate the files it needs to process.
3. Check version compatibility
Ensure your @ngtools/webpack version matches your Angular core version. Mismatched versions often cause context-related errors. Run this command to check:
npm list @ngtools/webpack @angular/core
If versions don’t align, upgrade or downgrade @ngtools/webpack to match your Angular version (e.g., Angular 15 needs @ngtools/webpack@15.x.x).
4. Clear Webpack cache
Sometimes stale cache data can cause the plugin to misread source file paths. Delete the node_modules/.cache directory or run:
npx webpack --clean
Then re-run your build.
Final Notes
This error is all about the plugin not having enough context to find your source files. By setting up the AngularCompilerPlugin properly, verifying your tsconfig, and ensuring version compatibility, you should be able to resolve it quickly.
内容的提问来源于stack exchange,提问作者Stepan Suvorov

