在我的 Angular 14 应用程序中使用 dayjs 会导致优化救助警告

Tho*_*mas 7 angular dayjs

我对 Angular 还很陌生,在我们的项目中,我们最近切换到了 Angular 14.2.12。我们使用 moment.js 进行基于时间的计算和日期时间解析。但在切换到 Angular 14 后,由于 moment.js,我们收到了优化救助警告:

Warning: C:\Users\**\worklist\worklist.component.ts depends on 'moment'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies
Run Code Online (Sandbox Code Playgroud)

moment.js 项目本身在其项目状态页面(https://momentjs.com/docs/#/-project-status/)上建议切换到另一个更适合现代 tree-shaking 算法等的日期库。

我们决定使用 dayjs,因为它的语法似乎与 moment.js 非常相似。但是在将 dayjs 添加到我们的项目并将用法从 moment.js 切换到 dayjs 后,优化警告再次出现在日志中,现在抱怨dayjs:

Warning: C:\Users\**\worklist\worklist.component.ts depends on 'dayjs'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies
Run Code Online (Sandbox Code Playgroud)

在提到的组件中,我们像这样使用dayjs:

import dayjs from 'dayjs';
.
.
.
this.importantDate = dayjs(json.impDate, 'YYYY-MM-DD').format(DATE_FORMAT)
Run Code Online (Sandbox Code Playgroud)

我认为 dayjs 库是 ES6 库,而不是 CommonJS 库格式。

我尝试使用 dayjs 文档中的另一种导入语法:

import * as dayjs from 'dayjs'
Run Code Online (Sandbox Code Playgroud)

那行不通。

我引用图书馆的方式有问题吗?

我尝试使用 dayjs 文档中的另一种导入语法:

import * as dayjs from 'dayjs'
Run Code Online (Sandbox Code Playgroud)

那行不通。

JSO*_*ulo 0

您的假设是错误的,DayJS 是在 CommonJS 中提供的并且缺乏 ESM 支持。这是一个已知问题,可在 GitHub 上跟踪:https ://github.com/iamkun/dayjs/issues/1765

DayJS v2 将会支持 ESM,有一个 v2 alpha 版本,您可以尝试一下 ( 2.0.0-alpha.2)。但尚不清楚稳定版 v2 何时发布。

虽然 Moment 和 dayjs 都无法在构建过程中进行优化,但 dayjs 的大小要小得多。Moment 缩小后约为 58kB 大,DayJS 约为 7kB(请参阅momentdayjsnpm 包)。所以从 moment 切换到 DayJS 绝对是性能上的提升。