How to import plotly.js into TypeScript?
Asked Answered
M

7

26

I'm trying to import plotly.js into TypeScript. Plotly.js is installed using npm. In my TypeScript file I use

import 'plotly.js';

It's OK but I'm getting error on code like Plotly.<member>:

error TS2304: Cannot find name 'Plotly'

When I try

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

I'm getting

error TS2307: Cannot find module 'plotly.js'.
Magneton answered 22/8, 2016 at 16:26 Comment(1)
You can use the previous version if the current one has issues.Chlorobenzene
M
10

Ended up with:

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

(Referring to index-basic.js as I need just the basic functionality, use index.js for the full library.)

EDIT (Feb 2018):

The preferred way now is adding path into tsconfig.json file, like this:

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

and then import in .ts file like

import * as Plotly from 'plotly.js';

Note: in the path I included only core.js, which contains scatter graphs, you can import other graphs as you need.

(I'm using it with Angular CLI - Angular 5.2 and Typesript 2.7.1)

Magneton answered 31/8, 2016 at 11:30 Comment(3)
I am doing var Plotly = require('plotly.js/dist/plotly.js') which is also working fine. Do you know, how both are different?Indulge
@yugantarkumar I only include basic module (I needed only scatter graph). You inlcude the full library. Check this link github.com/plotly/plotly.js/blob/master/dist/README.mdMagneton
I only searched for this issue because Plotly.js was not working on IE11. @yugantarkumar version worked for me on IE11 but some error related to vertx occured. The final solution for me was as @Magneton added (Feb 2018) but "../node_modules/plotly.js/lib/index-basic.js" (core.js wasn't enough to render basic charts).Denticulation
C
27

There is a Definitely Typed version available for plotly.js (Github link). This allows you to use the plain Javascript version inside Typescript. Follow these steps to setup your environment:

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

Then in your code you can do the following (example taken from 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);

Finally you need to convert the Typescript to javascript with tsc and prepare the code to be included in you webpage with browserify.

This also works now with ionic 2! Make sure you manually add the following packages:

npm install --save glslify
npm install --save mapbox-gl
Chrysanthemum answered 16/6, 2017 at 6:30 Comment(4)
plotly.js can also be used in ionic 2Chrysanthemum
I'm getting 404 errors using typed plotly: node_modules/plotly.js/src/traces/bar.js 404 (Not Found), node_modules/plotly.js/src/traces/box.js 404 (Not Found) and so on. Did you have this problem?Phototransistor
You could just write import Plotly from 'plotly.js'; as the library has a line export as namespace Plotly;Brachylogy
what type do I use that contains everything needed for a chart? data, and layout and config etc in one type?Noblenobleman
U
11

Types for plotly.js basic & Co.

You can also use types together with the partial npm bundles like basic or cartesian, starting in v1.39.0. Example for plotly.js basic (contains scatter, pie and bar):

npm i plotly.js-basic-dist
npm i -D @types/plotly.js

Add the following in tsconfig.json:

"compilerOptions": {
  // make aliases absolute imports relative to the project root
  "baseUrl": "./",                
  "paths": {
    "plotly.js-basic-dist": [
      "node_modules/@types/plotly.js"
    ]
  }
}

Above paths config just maps your imported plotly.js-basic-dist package to those types defined in @types/plotly.js, so you can use them with plotly.js-basic-dist. More Infos:

Urgency answered 11/11, 2018 at 17:7 Comment(3)
Nice. When using Create React App, this needs some trickery using "extends" to fix its build process: The following changes are being made to your tsconfig.json file: compilerOptions.paths must not be set (aliased imports are not supported). But that trickery works fine too.Disregard
Thanks that worked. Also make the changes @Disregard mentions.Zima
Thanks. Electron also only works with the dist bundles and this solved it.Gylys
M
10

Ended up with:

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

(Referring to index-basic.js as I need just the basic functionality, use index.js for the full library.)

EDIT (Feb 2018):

The preferred way now is adding path into tsconfig.json file, like this:

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

and then import in .ts file like

import * as Plotly from 'plotly.js';

Note: in the path I included only core.js, which contains scatter graphs, you can import other graphs as you need.

(I'm using it with Angular CLI - Angular 5.2 and Typesript 2.7.1)

Magneton answered 31/8, 2016 at 11:30 Comment(3)
I am doing var Plotly = require('plotly.js/dist/plotly.js') which is also working fine. Do you know, how both are different?Indulge
@yugantarkumar I only include basic module (I needed only scatter graph). You inlcude the full library. Check this link github.com/plotly/plotly.js/blob/master/dist/README.mdMagneton
I only searched for this issue because Plotly.js was not working on IE11. @yugantarkumar version worked for me on IE11 but some error related to vertx occured. The final solution for me was as @Magneton added (Feb 2018) but "../node_modules/plotly.js/lib/index-basic.js" (core.js wasn't enough to render basic charts).Denticulation
F
8

TS support

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

or

yarn add --dev @types/plotly.js`

and

import { PlotData } from "plotly.js"; // or whatever you need

⚠️Don't install @types in dependencies since they are used exclusively for development purposes.

Problem

Since you add types for plotly.js, you expect to import stuff from plotly.js instead of a specific module. This is all good until you want to use it with react i.e. react-plotly + plotly.js ☹️

I know you didn't mention React explicitly, but I figured you or anyone else with a similar issue might find this useful.

I am not sure about your bundling approaches, however, I'm using Webpack 4 and currently investigating a react-plotly + plotly.js-basic-dist combination.

Possible combinations are:

More about customising plotly bundles.

This brings the bundle size down significantly and the sun shines upon us once again.

BUT...

Since this approach will require a factory and custom dist, these, as of this writing, don't have types

import Plotly from "plotly.js-basic-dist";
import createPlotlyComponent from "react-plotly.js/factory";
const Plot = createPlotlyComponent(Plotly);

FIX

  1. Create a @types folder

    enter image description here

  2. Add typeRoots to tsconfig.json

    enter image description here

N.B. The following approach did fix the types for the above imports, but I still have a failing compilation, which I didn't manage to fix following the accepted answer: enter image description here

Hope you have a better experience!


UPDATE

I fixed the compiling issue. It was because react-plotly.js was being bundled in the 'dependencies`. For my case vendor deps are handled like this:

/**
 * 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;

Instead I moved react-plotly.js to the devDependencies and it works fine now.

Foley answered 25/10, 2018 at 10:56 Comment(0)
L
2

If the npm library you are importing does not provide type declarations itself, you'll have to import them yourself. The preferred tool is typings.

For plotly, it seems someone already made a declaration file. So once you have typings installed (npm i -g typings) you can search for the type declaration of plotly (typings search plotly). You'll see that there is a declaration file available on Definitely Typed. After you initialize typings for your project (typings init), you can install the declaration file (typings i --global --save plotly.js).

Notice the --global. This specific declaration file is a global declaration file. This means that you don't have to import any types, as the types are available everywhere in your project. Eg.

// app.ts
let myPlotlyConfig: PlotlyConfig
Leyte answered 22/8, 2016 at 16:58 Comment(1)
Generally, you're right with the typings. The ones for Plotly are just in a very early stadium, just 1 function actually so it is not usable yet. Anyway +1Magneton
F
1

Install plotly.js using NPM:

npm install --save plotly.js

Then in component or service wherever you want to use import like:

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
]);

Use plotly lib as below:

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

Plotly.newPlot('test', data);
Fugacious answered 18/12, 2017 at 16:37 Comment(0)
A
1

Could not find a declaration file for module 'plotly.js/dist/plotly.js'. 'C:/Users/spriy28/TEST2/tst/node_modules/plotly.js/dist/plotly.js' implicitly has an 'any' type.


To remove the error use this.

Add noImplicitAny: false in tsconfig json file to remove the error.

Alesiaalessandra answered 19/4, 2021 at 14:46 Comment(1)
Its really very helpful.Cychosz

© 2022 - 2024 — McMap. All rights reserved.