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

使用react-plotly.js时npm run build遇TypeScript语法错误

解决TypeScript编译报错“',' expected”问题

针对你在TypeScript React项目的JS文件中使用react-plotly.js时遇到的编译错误,可按以下步骤解决:

  • 首先安装Plotly的类型定义包(如果未安装):

    npm install @types/plotly.js --save-dev
    
  • 处理window.Plotly的类型识别问题,有两种常用方式:

    1. 类型断言方式:修改代码为

      import createPlotlyComponent from 'react-plotly.js/factory';
      const Plot = createPlotlyComponent(window.Plotly as any);
      

      若要更严谨,可引入Plotly类型后断言:

      import createPlotlyComponent from 'react-plotly.js/factory';
      import type { Plotly } from 'plotly.js';
      
      const Plot = createPlotlyComponent(window.Plotly as Plotly);
      
    2. 扩展Window接口方式:在项目的全局类型定义文件(如src/types/global.d.ts)中添加:

      interface Window {
        Plotly: import('plotly.js').Plotly;
      }
      

      之后原代码即可正常使用,无需修改。

  • 额外检查:若项目tsconfig.json中开启了checkJs且包含JS文件编译,确保上述类型处理完成后,TS就能正确识别window.Plotly,消除语法报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:55:31