解决 Angular 18 Polyfills 警告
问题描述
升级到 Angular 18 后,执行 ng serve
命令时出现以下警告提示:
▲ [WARNING] Polyfill for "@angular/localize/init" was added automatically. [plugin angular-polyfills]
In the future, this functionality will be removed. Please add this polyfill in the "polyfills" section of your "angular.json" instead.
该问题通常出现在项目进行了 Angular 版本升级后,尤其是当项目中使用了 @angular/localize
包(Angular 国际化支持)时。根据警告提示,Angular 构建工具当前自动注入了 @angular/localize/init
polyfill,但这种行为在未来版本中将被移除。
解决方案
项目类型区分
请先确认您的项目类型:
- Angular 应用程序:使用下面第一种解决方案
- Angular 库项目:使用第二种解决方案
对于 Angular 应用程序
- 修改 angular.json 文件
在构建配置的polyfills
数组中添加"@angular/localize/init"
:
json
{
"projects": {
"your-project-name": {
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser-esbuild",
"options": {
"polyfills": [
"src/polyfills.ts",
"@angular/localize/init" // 添加此行
],
// 其他配置...
}
}
}
}
}
}
- 清理 polyfills.ts 文件
移除src/polyfills.ts
中对@angular/localize/init
的导入:
ts
// 删除此行 ▼
import '@angular/localize/init'; // 删除或注释掉该行
// 其他polyfill保留...
- 删除空 polyfill 文件(可选)
如果polyfills.ts
文件在清理后为空,可以安全删除它,并在angular.json
中移除对该文件的引用:
json
"options": {
"polyfills": [
// "src/polyfills.ts", // 已删除
"@angular/localize/init"
],
// ...
}
对于 Angular 库项目
- 修改公开 API 文件
使用三斜线指令替换import
语句:
ts
/// <reference types="@angular/localize" /> // 替换 import 语句
// 其他导出...
- 更新 TypeScript 配置
在库的tsconfig.json
中添加类型声明:
json
{
"compilerOptions": {
"types": ["@angular/localize"],
// 其他配置...
}
}
- 移除无效引用
确保库项目中不再存在对@angular/localize/init
的导入语句,因为库项目不使用angular.json
polyfill 配置。
原因解释
此警告源于 Angular 18 对 polyfill 管理方式的变更:
- Angular 构建工具将移除自动注入 polyfill 的功能
@angular/localize
需要特定初始化代码才能正常工作- 显式声明 polyfill 可提升构建透明度和可维护性
注意事项
- 确保已在
package.json
中安装正确版本的@angular/localize
:json"dependencies": { "@angular/localize": "^18.0.3" }
- 如果项目未使用国际化功能,可考虑卸载
@angular/localize
而不是添加 polyfill - 修改后执行
ng serve
验证警告是否消失
修改完成后重新启动开发服务器,警告信息将不再出现。此变更确保项目遵循 Angular 最新最佳实践,避免未来版本升级时出现兼容性问题。