You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular HMR引发TypeError:构造URL失败(无效URL)求解决方案

Angular 19 HMR模式下出现"Failed to construct 'URL': Invalid URL"错误的修复方案

问题重现

将Angular 18应用升级至19.2.6后,启用HMR运行ng serve时,控制台大量抛出:

TypeError: Failed to construct 'URL': Invalid URL
    at footer.component.ts:11:29

禁用HMR(ng serve --no-hmr)可规避该问题,但希望保留HMR开发特性。

可能原因分析

  1. 相对路径解析异常:HMR模式下资源路径的基准上下文发生变化,模板中使用的相对路径(如./assets/Text.png)无法被正确解析为有效URL。
  2. View Transitions与HMR冲突:Angular 19的View Transitions特性在HMR刷新时,内部URL处理逻辑存在兼容性问题。
  3. 版本bug:Angular 19.2.x早期版本可能存在HMR相关的已知问题。

修复方案

方案1:修正资源路径为绝对路径

修改footer.component.html中的图片路径,去掉相对路径前缀./:

<!-- 原代码 -->
<img src="./assets/Text.png" alt="" class="footer-logo-text" />

<!-- 修改后 -->
<img src="/assets/Text.png" alt="" class="footer-logo-text" />

绝对路径会以应用根目录为基准,避免HMR模式下的路径解析混乱。

方案2:在HMR模式下禁用View Transitions

在app.config.ts的路由配置中,给View Transitions添加启用条件,仅在非HMR环境下生效:

// 修改withViewTransitions配置
withViewTransitions({
  enabled: () => !import.meta.env.HMR, // HMR模式下禁用
  onViewTransitionCreated: ({ transition, to }) => {
    const router = inject(Router);
    const toTree = createUrlTreeFromSnapshot(to, []);
    if (
      router.isActive(toTree, {
        paths: 'exact',
        matrixParams: 'exact',
        fragment: 'ignored',
        queryParams: 'ignored',
      })
    ) {
      transition.skipTransition();
    }
  },
}),

如果项目不需要View Transitions特性,也可以直接移除withViewTransitions配置项。

方案3:升级Angular至最新稳定版

当前使用的19.2.6可能存在HMR相关bug,升级到19.x系列的最新版本(如19.3.x):
执行命令:

ng update @angular/core @angular/cli

升级后重新启动HMR,验证问题是否解决。

方案4:检查HMR初始化配置

确保main.ts中的HMR初始化代码正确:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

if (import.meta.env.HMR) {
  import('@angular-devkit/build-angular/src/webpack/hmr').then(hmr => {
    hmr.hmrModule(import.meta, bootstrapApplication(AppComponent, appConfig));
  });
} else {
  bootstrapApplication(AppComponent, appConfig);
}

同时确认angular.json中serve配置的HMR选项已正确开启:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "hmr": true,
    "browserTarget": "your-project-name:build"
  }
}

验证步骤

  1. 优先尝试方案1,修改路径后启动HMR,观察错误是否消失。
  2. 若方案1无效,尝试方案2禁用HMR下的View Transitions。
  3. 前两种方案都不生效时,执行方案3升级依赖版本。

内容的提问来源于stack exchange,提问作者display-name unset

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:13:19