TS 支持
npm install --save-dev @types/plotly.js`
或
yarn add --dev @types/plotly.js`
和
import { PlotData } from "plotly.js"; // or whatever you need
⚠️不要在依赖项中安装 @types,因为它们专门用于开发目的。
问题
由于您为 plotly.js 添加了类型,因此您希望从 plotly.js 而不是特定模块导入内容。这一切都很好,直到您想将它与 react 一起使用,即 react-plotly + plotly.js ☹️
我知道你没有明确提到 React,但我想你或其他有类似问题的人可能会觉得这很有用。
我不确定您的捆绑方法,但是,我正在使用 Webpack 4,目前正在研究 react-plotly + plotly.js-basic-dist 组合。
可能的组合有:
更多关于customising plotly bundles。
这大大减小了捆绑包的大小,阳光再次照耀着我们。
但是……
由于这种方法需要工厂和自定义 dist,因此在撰写本文时,这些还没有类型
import Plotly from "plotly.js-basic-dist";
import createPlotlyComponent from "react-plotly.js/factory";
const Plot = createPlotlyComponent(Plotly);
修复
-
创建一个@types 文件夹
-
将 typeRoots 添加到 tsconfig.json
注意以下方法确实修复了上述导入的类型,但我仍然有一个失败的编译,我没有按照接受的答案修复它:
希望你有更好的体验!
更新
我修复了编译问题。这是因为 react-plotly.js 被捆绑在“依赖项”中。对于我的案例,供应商部门的处理方式如下:
/**
* Given an array of files this will produce an object which contains the values for the vendor entry point
*/
function makeVendorEntry(config) {
const packageJson = require('../package.json');
const vendorDependencies = Object.keys(packageJson['dependencies']);
const vendorModulesMinusExclusions = vendorDependencies.filter(vendorModule =>
config.mainModules.indexOf(vendorModule) === -1 && config.modulesToExclude.indexOf(vendorModule) === -1);
return vendorModulesMinusExclusions;
}
exports.makeVendorEntry = makeVendorEntry;
相反,我将 react-plotly.js 移至 devDependencies,它现在可以正常工作了。