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

Angular 12 安装 Plotly.js 出现 TypeScript 编译及构建错误如何解决

Angular 12 集成 angular-plotly.js 报错解决方案

一、首次安装出现TypeScript编译错误修复方案

核心原因

版本不匹配+导入配置错误,最新版angular-plotly.js仅支持Angular 14+,Angular 12需适配4.x版本。

修复步骤

  1. 卸载错误安装的版本,安装匹配版本:
    npm uninstall angular-plotly.js plotly.js && npm install angular-plotly.js@4.x plotly.js-dist-min --save
  2. 调整AppModule配置:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PlotlyModule } from 'angular-plotly.js';
// 导入预编译的plotly包,避免源码打包依赖问题
import * as Plotly from 'plotly.js-dist-min';

// 全局绑定Plotly实例
PlotlyModule.plotlyjs = Plotly;

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, PlotlyModule],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. 调整tsconfig.json配置,关闭类型校验冲突:
    在compilerOptions节点下新增以下配置:
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

二、修复TS错误后构建报错解决方案

核心原因

Angular 12 开始默认移除了Node.js核心模块的polyfill,若使用plotly.js源码包会缺失依赖。

修复步骤

  1. 优先推荐用预编译的plotly.js-dist-min替代plotly.js,此方法无需额外配置polyfill,若已按上一步安装该包可直接跳过后续步骤。
  2. 若必须使用plotly.js源码包,按以下操作配置polyfill:
  • 安装依赖包:
    npm install plotly.js stream buffer util process --save
  • 在src/polyfills.ts末尾新增配置:
declare var window: any;
window.global = window;
window.process = require('process');
window.Buffer = require('buffer').Buffer;
  • 调整angular.json配置,允许CommonJS依赖:
    找到projects -> [你的项目名] -> architect -> build -> options节点,新增:
"allowedCommonJsDependencies": [
  "plotly.js",
  "buffer",
  "stream",
  "util"
]

三、生效验证

在任意组件模板中加入测试代码,启动ng serve确认图表可正常渲染:

<plotly-plot 
  [data]="[{x: [1, 2, 3, 4], y: [10, 15, 13, 17], type: 'scatter'}]"
  [layout]="{title: 'Plotly集成测试图表'}"
></plotly-plot>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 20:54:02