How to importing an external JavaScript lib


#1

Developing Plugins i want to import an external JavaScript lib ( techan.js)

npm install teachan --save
npm install d3 --save
and adding code in rendering.js:
import * as d3 from ‘d3’;
import techan from ‘./libs/techan’

but I got this…
Screenshot from 2017-07-26 13-38-28


#2

D3 is already included in Grafana 4.x

To include lib just place it along side your code and import it using import statement or systemjs.


#3

Just adding a note here. npm install installs the d3 code into the node_modules directory. That is not available to your plugin. It will only be available to the build tools (grunt or similar). You have to copy the js file from your node_modules into the src directory of your plugin.


#4

I’ve just had a similar issue. d3-scale-chromatic is no longer part of d3 and I had to copy and paste its source in order to make it work in my plugin. I don’t think this is a very good solution.

You mention that “npm installs d3 code into the node_modules directory”. Do you mean core grafana node_modules directory or the plugins directory?

I’ve installed the d3-scale-chromatic into plugin’s node_modules but wasn’t able to import it - grafana tries to load it from public directory (http://localhost:3000/public/d3-scale-chromatic). Is there some way to make it load from the plugin’s node_modules directory? And if not, have you thought about implementing it? I think it would help to achieve much cleaner solution in case when plugin needs to use an external library.
Thanks for reply.


#5

Hey.

For this problem I created https://github.com/CorpGlory/grafana-plugin-template-webpack where you can get one bundle with your libs using npm and webpack


#6

For external JS libs, you currently have to include them in the plugin. Here is an example: https://github.com/grafana/worldmap-panel/blob/master/src/worldmap.js#L3


#7

One follow-up question,

In my plugin, I import d3 (v3) lib as @daniellee mentioned but it starts giving an issue when another plugin on same dashboard loads a different version of d3.

On plugin initialization, it uses the correct version of ‘d3.js’ library as mentioned in code but on a different workflow when data is received, plugin starts using different version of d3 (loaded by different plugin).

For e.g. Bubble-chart plugin imports d3 library
like: https://github.com/digrich/bubblechart-panel/blob/b8194655f84ab3a3528244fdcebd75f7c86cab4e/src/bubble_ctrl.js#L2 but it starts getting a conflict with ‘Diagram’ plugin d3 library (older version) and starts breaking my code.


#8

If you are using d3 then you do not need to include it in your code. It is already loaded by Grafana - see list of exposed components here: