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

如何在Angular中通过本地版本正确引入Plotly类型定义

问题描述

我查了多个Plotly相关包,发现angular-plotly已经停更了。于是我下载了plotly.min.js放到项目资源里,在angular.json中这样引入:

"scripts": [
    "src/assets/scripts/plotly.min.js"
]

目前只有在tsconfig.json里关闭noImplicitAny(配置如下)才能正常运行:

"noImplicitAny": false,

请问怎么使用@types/plotly.js类型定义?或者我的做法有没有根本性错误?

完整tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true, 
    "noImplicitAny": false, // this is probably not really clever... https://blog.atomist.com/declaration-file-fix/
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
      "dom"
    ],
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strictPropertyInitialization": false
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

解决方案

你的做法本身没问题,只是缺少TypeScript类型定义导致必须关闭noImplicitAny。以下是正确配置@types/plotly.js的步骤:

  1. 安装类型定义包
    在项目根目录执行npm命令安装@types/plotly.js:
npm install @types/plotly.js --save-dev
  1. 配置TypeScript识别全局类型
    修改tsconfig.json的compilerOptions,确保TypeScript能找到plotly的类型定义:
  • 如果没有指定types数组,直接添加:
"compilerOptions": {
  // 其他配置...
  "types": ["plotly.js"]
}
  • 如果已经有types数组,把plotly.js追加进去即可。
  1. 恢复noImplicitAny为true
    把tsconfig.json里的"noImplicitAny": false改回true,这能保持TypeScript的严格类型检查,避免潜在的类型错误。

  2. 在代码中使用Plotly
    现在你可以在组件中直接使用全局的Plotly对象,并且能获得完整的类型提示:

export class YourComponent implements OnInit {
  ngOnInit(): void {
    const data = [
      {
        x: [1, 2, 3],
        y: [4, 1, 2],
        type: 'bar'
      }
    ];
    const layout = {title: 'Sample Plot'};
    Plotly.newPlot('plotDiv', data, layout);
  }
}

额外说明
  • 如果你不想在tsconfig里全局引入类型,也可以在单个组件文件顶部手动声明类型:
declare var Plotly: typeof import('plotly.js');

这种方式适合只在少数组件中使用Plotly的场景。

  • 直接引入plotly.min.js的方式是可行的,尤其是在官方Angular封装包停更的情况下,这种“手动引入+类型定义”的方案是合理的替代方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:27:23