是不是不需要 core-js 了?

Is not core-js needed anymore?

我已经将一个 Angular 项目从版本 7 更新到版本 8。一切运行顺利,原理图完成了它的工作(也许),我们很好(项目甚至在生产中)。当我们更新 Angular CLI 时,我们总是生成一个新项目以查看真正的差异并从中学习,例如新的依赖项、配置等。

使用 Angular CLI 8.0.4 生成新的 Angular 项目时,新应用没有 core-js 作为依赖项:

"dependencies": {
    "@angular/animations": "~8.0.1",
    "@angular/common": "~8.0.1",
    "@angular/compiler": "~8.0.1",
    "@angular/core": "~8.0.1",
    "@angular/forms": "~8.0.1",
    "@angular/platform-browser": "~8.0.1",
    "@angular/platform-browser-dynamic": "~8.0.1",
    "@angular/router": "~8.0.1",
    "rxjs": "~6.4.0",
    "tslib": "^1.9.0",
    "zone.js": "~0.9.1"
  }

分析已构建项目 core-js 上的包不存在: 在我的 项目中,使用 Angular CLI 更新,core-js 存在并且存在于最终包中:

"dependencies": {
    "@angular/animations": "~8.0.3",
    "@angular/cdk": "~8.0.1",
    "@angular/common": "~8.0.3",
    "@angular/compiler": "~8.0.3",
    "@angular/core": "~8.0.3",
    "@angular/forms": "~8.0.3",
    "@angular/platform-browser": "~8.0.3",
    "@angular/platform-browser-dynamic": "~8.0.3",
    "@angular/router": "~8.0.3",
    "@auth0/angular-jwt": "2.1.1",
    "@hackages/ngxerrors": "~8.0.0",
    "@ng-bootstrap/ng-bootstrap": "5.0.0-rc.1",
    "@ngx-loading-bar/core": "~4.2.0",
    "@ngx-loading-bar/http-client": "~4.2.0",
    "@nicky-lenaers/ngx-scroll-to": "~2.0.0",
    "@swimlane/ngx-charts": "~12.0.1",
    "bootstrap": "~4.3.1",
    "core-js": "~2.6.9",
    "d3-scale": "~3.0.0",
    "d3-shape": "~1.3.5",
    "date-fns": "2.0.0-beta.2",
    "ngx-perfect-scrollbar": "~8.0.0",
    "ngx-toastr": "~10.0.4",
    "rxjs": "~6.5.2",
    "tslib": "~1.10.0",
    "xlsx": "~0.14.3",
    "zone.js": "~0.9.1"
  }

为什么会出现这种行为?删除 core-js 作为依赖是否安全?更新原理图是否缺少这个?在最新项目上安装 npm 依赖项时,我从 core-js 收到 post-install 消息,但它没有明确出现在包描述中。

根据this文章。

Note that core-js has been updated to v3, and is now directly handled by the CLI itself, so it’s no longer needed as a dependency of your application.

如果您查看 Angular 7 或更早版本项目中的 src/polyfills.ts,您会看到一堆注释和注释掉的导入语句,这些语句允许您通过取消注释为各种浏览器添加 polyfill他们 - 大多数来自 core.js.

在 Angular 8 中,随着 Differential Loading 的出现,CLI 将根据您在 browserslist 文件中的要求和你的 tsconfig 文件。

The Angular CLI handles differential loading for you as part of the build process for deployment. The ng build command produces the necessary bundles used for differential loading, based on your browser support requirements and compilation target.

ng8 中与 core-js 的区别在于,由于 CLI 正在处理 polyfill,因此 core-js 是 CLI 的依赖项。因此,即使您在升级到 ng8 的过程中卸载了 core-js,您也会看到它仍在您的 node_modules 文件夹中,但您不必管理安装的是哪个版本。

将项目和 CLI 升级到 angular8 后,我建议您这样做:

  1. 用新生成的 ng8 或更高版本项目中的同一文件的内容替换 polyfills.ts 的内容
  2. 从您的项目中卸载 core-js。

现在您可以构建项目,CLI 会处理 polyfill。