2016-08-22 91 views
4

我正試圖將plotly.js導入到TypeScript中。 Plotly.js使用npm進行安裝。在我的打字稿文件我用如何將plotly.js導入到TypeScript中?

import 'plotly.js'; 

這是確定的,但我得到的錯誤代碼上像Plotly.<member>

error TS2304: Cannot find name 'Plotly' 

當我嘗試

import Plotly = require('plotly.js'); 

我越來越

error TS2307: Cannot find module 'plotly.js'. 

回答

4

結束:

declare function require(moduleName: string): any; 
var Plotly = require('plotly.js/lib/index-basic.js'); 

(參照指數basic.js,因爲我只需要基本功能,爲全面圖書館利用index.js)

編輯(Feb 2018):

現在的首選方法是將路徑添加到tsconfig.json文件中,如下所示:

"compilerOptions": { 
    "paths": { 
     "plotly.js": [ 
      "../node_modules/plotly.js/lib/core.js" 
     ] 
    } 
} 

然後導入在.ts文件中像

import * as Plotly from 'plotly.js'; 

注:在路上,我只包括core.js,其中包含scatter圖表,因爲你需要,你可以導入其他圖形。

(我使用它與角CLI - 角5.2和2.7.1 Typesript)

+0

我正在做'var Plotly = require('plotly.js/dist/plotly.js')'這也正常工作。你知道嗎,兩者有什麼不同? –

+1

@yugantarkumar我只包含基本模塊(我只需要散點圖)。你包括完整的圖書館。檢查這個鏈接https://github.com/plotly/plotly.js/blob/master/dist/README.md – eXavier

2

如果npm庫你正在導入本身不提供類型聲明,你必須自己導入它們。首選工具是typings

對於情節,似乎有人已經做出了聲明文件。所以一旦你安裝了打字機(npm i -g typings),你可以搜索劇情類型聲明(typings search plotly)。您會看到在Definitely Typed上有一個聲明文件。在初始化項目的類型(typings init)後,可以安裝聲明文件(typings i --global --save plotly.js)。

請注意--global。該特定聲明文件是全局聲明文件。這意味着您不必導入任何類型,因爲類型在您的項目中隨處可見。例如。

// app.ts 
let myPlotlyConfig: PlotlyConfig 
+0

Ge一般來說,你是正確的打字。 Plotly的只是在一個非常早的體育場內,實際上只有1個功能,所以它現在還不可用。無論如何+1 – eXavier

6

沒有爲plotly.js可用絕對類型版本(Github link)。這使您可以在Typescript中使用簡單的Javascript版本。請按照以下步驟設置你的環境:

npm install --save plotly.js 
npm install --save @types/plotly.js 

然後在你的代碼,你可以做以下(從Github採取爲例):

import * as Plotly from 'plotly.js'; 

const data: Plotly.BarData[] = [ 
    { 
    x: ['giraffes', 'orangutans', 'monkeys'], 
    y: [20, 14, 23], 
    type: 'bar' 
    } 
]; 

Plotly.newPlot('test', data); 

最後,您需要的打字稿轉換爲JavaScript和tsc和準備代碼將包含在您的網頁browserify

這也適用於離子2!請確保您手動添加以下軟件包:

npm install --save glslify 
npm install --save mapbox-gl 
+1

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供鏈接供參考。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – thewaywewere

+0

謝謝@thewaywewere!我相應地修改了我的答案。 –

+0

plotly.js也可用於離子2 –

1

使用NPM安裝plotly.js:

npm install --save plotly.js 

然後在組件或服務,無論你想使用進口,如:

import Plotly from 'plotly.js/lib/core'; 
Plotly.register([ 
require('plotly.js/lib/heatmap'), 
require('plotly.js/lib/bar'), 
require('plotly.js/lib/pie') // can include as many plot types as you want 
]); 

使用如下圖示:

const data: Plotly.BarData[] = [ 
{ 
    x: ['giraffes', 'orangutans', 'monkeys'], 
    y: [20, 14, 23], 
    type: 'bar' 
} 
]; 

Plotly.newPlot('test', data); 
相關問題