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

升级Angular 19后import().then加载xlsx库失效问题求助

Angular 19 动态导入xlsx构建后报错的解决办法

问题概述

Angular 17及更早版本中,通过以下动态导入xlsx的代码可正常实现Excel导出:

import('xlsx').then(xlsx => {
  const ws: any = xlsx.utils.json_to_sheet(json);

  const wb: any = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(wb, ws, 'teste9');

  xlsx.writeFile(wb, 'test.xlsx');
});

升级到Angular 19后,ng serve开发环境运行正常,但ng build构建后的代码抛出错误:

ERROR TypeError: Cannot read properties of undefined (reading 'json_to_sheet')

已尝试但无效的操作:

  • 使用相对路径导入../../../../node_modules/xlsx
  • 修改构建器配置
  • 创建新标准配置项目重复导入操作

可行解决方案

1. 导入xlsx的ESM兼容版本

动态导入时指定xlsx的ESM入口文件xlsx.mjs,替换原导入代码:

import('xlsx/dist/xlsx.mjs').then((xlsx) => {
  const ws: any = xlsx.utils.json_to_sheet(json);
  const wb: any = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(wb, ws, 'teste9');
  xlsx.writeFile(wb, 'test.xlsx');
});

2. 允许CommonJS依赖构建

在angular.json的构建配置中,将xlsx添加到allowedCommonJsDependencies列表,确保构建时正确处理该依赖:

"architect": {
  "build": {
    "options": {
      // 保留原有配置
      "allowedCommonJsDependencies": [
        "xlsx"
      ]
    }
  }
}

3. 改用静态导入(备选方案)

若动态导入仍存在问题,尝试直接静态导入xlsx包:

import * as XLSX from 'xlsx';

// 业务代码直接调用
const ws: any = XLSX.utils.json_to_sheet(json);
const wb: any = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'teste9');
XLSX.writeFile(wb, 'test.xlsx');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 13:42:39