Angular CLI 1.7.3 SSR应用npm start报错:Cannot read property 'moduleType' of undefined
Hey there, let’s dig into this error you’re facing with your Angular SSR app built on CLI 1.7.3. That "moduleType" undefined error almost always ties back to how your server-side bundle is being imported or generated, so let’s go through actionable fixes step by step:
1. Verify You’re Building Both Client and Server Bundles
First up: make sure npm run build isn’t only creating the client-side files. Angular CLI 1.7.3’s SSR setup requires separate client and server builds to generate the AppServerModuleNgFactory properly.
- Check your
package.jsonscripts. If yourbuildcommand only runsng build --prod, you’re missing the server build. Update it to include both:"scripts": { "build:client": "ng build --prod", "build:server": "ng build --prod --app 1 --output-hashing=false", "build": "npm run build:client && npm run build:server" } - After updating, run
npm run buildagain and confirm yourdistfolder has aserversubdirectory (or equivalent server bundle files) alongside the client files.
2. Fix the AppServerModuleNgFactory Import in server.ts
Your current dynamic import approach might be failing because the module exports don’t actually contain the factory, or the path is wrong.
- Try replacing the dynamic import with a direct import pointing to your server bundle. For most 1.7.3 setups, the path looks like this:
import { AppServerModuleNgFactory } from '../dist/server/main-server.bundle'; - If you need to keep the dynamic import for some reason, add a debug log to check what’s actually being exported:
Run the server again—ifconsole.log('Server module exports:', (module as any).exports); const { AppServerModuleNgFactory } = (module as any).exports;AppServerModuleNgFactoryisn’t in the logged output, your server build didn’t generate it correctly (head back to step 1).
3. Ensure Dependencies Are Compatible with Angular 5.x
Angular CLI 1.7.3 targets Angular 5.x, so your Universal-related packages need to match this version range. Mismatched versions can break the NgFactory generation.
- Check your
package.jsonfor these dependencies and make sure they’re using^5.0.0versions:"@nguniversal/express-engine": "^5.0.0", "@nguniversal/module-map-ngfactory-loader": "^5.0.0" - If versions are off, update them with:
npm install @nguniversal/express-engine@^5.0.0 @nguniversal/module-map-ngfactory-loader@^5.0.0 --save
4. Clean Caches and Rebuild from Scratch
Old build caches can cause weird inconsistencies. Let’s wipe them out and start fresh:
rm -rf dist node_modules/.cache npm install npm run build
After going through these steps, try starting your server again. The error should resolve if the bundle is correctly generated and imported.
内容的提问来源于stack exchange,提问作者Pardeep Jain

