Angular7升级至Angular8时出现DOCUMENT导出缺失错误求助
Hey there! This error pops up because Angular 8 moved the DOCUMENT token from @angular/platform-browser to @angular/common. Even if you don’t have explicit imports of DOCUMENT in your own code, the generated ngfactory files (used during compilation) or third-party libraries might still be referencing the old import path. Here’s how to resolve it:
Step 1: Ensure You Ran the Official Angular Update Command
First, confirm you followed the Angular upgrade process correctly. Run these commands to make sure all core Angular packages are updated to version 8:
ng update @angular/cli @angular/core
This command handles most breaking changes automatically, including updating internal references to DOCUMENT.
Step 2: Update Third-Party Dependencies
The most likely culprit is an outdated library that still imports DOCUMENT from the old location. Check for outdated packages with:
npm outdated
Update all dependencies to versions that explicitly support Angular 8. For example, libraries like ng-bootstrap, @angular/material, or custom components often have Angular version-specific releases. After updating, run npm install to refresh your dependency tree.
Step 3: Use a TypeScript Shim to Redirect the Import
If updating a library isn’t feasible (e.g., it’s deprecated), create a shim file to re-export DOCUMENT from the correct location:
- Create a file named
platform-browser-shim.tsin yoursrcfolder:
// Re-export all existing exports from platform-browser export * from '@angular/platform-browser'; // Add the DOCUMENT token from @angular/common export { DOCUMENT } from '@angular/common';
- Update your
tsconfig.jsonto map@angular/platform-browserto this shim:
{ "compilerOptions": { // ... other existing options "paths": { "@angular/platform-browser": ["./src/platform-browser-shim"] } } }
This tells TypeScript to use your shim instead of the original module, ensuring DOCUMENT is found when referenced.
Step 4: Clean Build Artifacts
Cached files can sometimes cause lingering issues. Clear your build cache and reinstall dependencies:
rm -rf node_modules package-lock.json npm install ng cache clean ng build --clean
These steps should fix the missing DOCUMENT error. Let me know if you hit any roadblocks!
内容的提问来源于stack exchange,提问作者Ronald Bachata

