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

Angular 14项目引入Dayjs仍触发优化退出警告的问题求助

Angular 14.2.12中Dayjs触发CommonJS优化警告的解决方案

升级Angular至14.2.12后,原moment.js因CommonJS依赖触发优化退出警告,切换到语法相似的Dayjs后仍出现相同警告。组件中尝试过两种导入方式:

import dayjs from 'dayjs';

以及

import * as dayjs from 'dayjs';

均未解决问题。以下是具体解决方法:

1. 确认Dayjs版本并重新安装

Dayjs v1.10+已支持ES模块,但部分旧版本可能默认提供CommonJS格式。执行以下命令安装最新版:

npm install dayjs@latest

2. 配置Angular允许Dayjs的CommonJS依赖

在angular.json文件中,找到对应项目的build配置,在options节点下添加allowedCommonJsDependencies字段,将dayjs加入白名单:

"projects": {
  "your-project-name": {
    "architect": {
      "build": {
        "options": {
          // 其他配置
          "allowedCommonJsDependencies": [
            "dayjs"
          ]
        }
      }
    }
  }
}

此配置会让Angular构建时忽略Dayjs的CommonJS依赖警告。

3. 确保使用正确的ES模块导入语法

推荐使用默认导入方式,若需使用插件,同样采用ES模块导入:

import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 示例:导入中文语言包

dayjs.locale('zh-cn');
this.importantDate = dayjs(json.impDate, 'YYYY-MM-DD').format(DATE_FORMAT);

4. 验证生产构建的Tree Shaking配置

确保生产构建开启了优化(默认已开启),在angular.json的production配置中确认:

"configurations": {
  "production": {
    "optimization": true,
    // 其他生产配置
  }
}

Tree Shaking仅在生产构建阶段生效,开发环境下的警告不影响最终优化效果。

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:21:46