Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Webpack to inject Google Charts into my project?

Is there any way to use Google Charts in a React app? I have found react-google-charts which I have got working a bit, but it seems to lack much of the API of Google Charts, or is at the very least is undocumented. I'm also a little shy to use something in production that NPM stats show only has ~400 downloads in the last day.

However I can't find Google Charts alone on NPM and no way simply to import Charts from 'google-charts' like I had initially expected.

My next thought was to see if there is a way to import a library as a global variable.

1) How can I do that 2) If that's possible how do I include it in a react component like import { Line } from '???'

like image 926
1252748 Avatar asked Jun 02 '17 21:06

1252748


Video Answer


1 Answers

Use Webpack externals
By defining a library as external webpack simply export the global symbol for the library, much like (say for jQuery)

{
    1: function(...) {
        // simplified for illustrating
        module.exports = jQuery;
    }
}

So you could do something similar to this:

  1. Add a <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> or newer url from Charts homepage

  2. In your webpack configuration add:

    externals: {
      charts: 'google.charts'  // or any other alias you want, can be a regex too! check Webpack's doc for more
    }
    
  3. And import it as:

    import chart from 'charts'
    // do something!
    charts.load('current', {'packages':['corechart']});
    

Make sure to load Google Charts before loading your bundle.

For the ReactJS part, you need some way to get hold of the native DOM element in your script, by using refs or something.

P.S. I am not a react guy so maybe someone with react background may help

like image 179
riyaz-ali Avatar answered Sep 29 '22 18:09

riyaz-ali