Angular 应用里 index.html 的作用

时间:2023-02-06 12:14:38

index.html 位于应用程序的 src 文件夹中。 编译器在此文件的末尾动态添加所有 javascript 文件。

由于现在所有组件都是已知的,因此 html 文件调用根组件即 app-root。 根组件在 app.components.ts 中定义,它以 app.component.html 为目标。

这是 index.html 文件在 Visual Studio Code 环境中的样子:

<!doctype html>
 <html lang="en">
    <head>
       <meta charset="utf-8">
       <title>My Hello World App!</title>
       <base href="/">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
       <app-root></app-root>
    </body>
 </html>

选择器 app-root 对应的 Component 源代码:

import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'hello-world';
}

当在浏览器中提供并打开这个 Angular 应用程序时,脚本注入由编译器完成,这就是文件在浏览器中的样子:

Angular 应用里 index.html 的作用

其中黄色高亮区域是编辑器动态注入的。

上述代码的 vendor.js: 在幕后,Angular CLI 使用 Webpack,一个模块打包器。 除此之外,Webpack(在许多插件的帮助下)将项目代码和资产转换为 JavaScript 包。 这些包包含应用程序的所有代码,以及第三方代码(例如 Angular 和应用程序可能使用的其他库)。

当使用 ng build --prod 构建应用时,还会生成如下 artifacts:

Angular 应用里 index.html 的作用

包名称后的看似随机的字符串是哈希值,添加在此处是为了清除缓存。 也就是说,确保 Web 浏览器使用更新后的内容,而不是之前在本地存储的版本。 通常,如果应用程序的内容没有改变,那么即使多次构建,这些 hash 字符串也将保持不变。

  • main.js:应用程序代码和开发人员导入的所有内容
  • vendor.js:应用依赖的第三方代码
  • polyfills.js:允许在旧环境中使用新功能的 polyfill(例如,在过时的 Web 浏览器上使用 Angular)
  • runtime.js:Webpack 用于在运行时加载代码的实用程序代码