Angular路由懒加载模块报错:无法找到模块求助
Hey there! I totally get how frustrating it is when a setup that's always worked suddenly breaks after an update—let's get your lazy loading working again.
The Root Cause
Angular 6 introduced a new, recommended syntax for lazy loading modules, replacing the old string-based path format you're using. The syntax 'app/feed/feed.module#FeedModule' was deprecated in Angular 6, and with your updated CLI and core versions (6.0.x), this old approach won't resolve modules correctly anymore.
The Fix
Update your app-routing.module.ts to use the dynamic import() syntax instead. Here's how to adjust your route configuration:
Original Code (Problematic):
const rootRoutes: Routes = [ { path: '', redirectTo: 'feed', pathMatch: 'full' }, { path: 'feed', loadChildren: 'app/feed/feed.module#FeedModule' } ];
Updated Code (Working):
const rootRoutes: Routes = [ { path: '', redirectTo: 'feed', pathMatch: 'full' }, { path: 'feed', loadChildren: () => import('./feed/feed.module').then(m => m.FeedModule) } ];
Key Notes:
- We're using a relative path (
./feed/feed.module) instead of the absoluteapp/feed/...path—this aligns with Angular 6+'s module resolution rules and avoids path resolution issues. - The dynamic
import()syntax leverages native ES modules and works seamlessly with Webpack 4 (which Angular 6 uses under the hood), plus it gives you better type checking during development.
Verify Your Setup
Just to double-check, confirm these details are in place (which they look like they are from your code):
FeedModuleis properly exported infeed.module.tsFeedRoutingModuleis imported intoFeedModule- Your file structure matches the relative path you're using (you already confirmed this via VS Code, so you're good here)
Bonus Tip
If you have other lazy-loaded modules in your app, you'll need to update all of them to use this new syntax to avoid similar errors down the line.
Once you make this change, restart your dev server (ng serve) and the "Cannot find module" error should be gone!
内容的提问来源于stack exchange,提问作者Nicholas Pesa

