简体   繁体   English

我可以使用Webpack将Google图表插入到我的项目中吗?

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

Is there any way to use Google Charts in a React app? 有什么方法可以在React应用程序中使用Google Charts吗? 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. 我发现我做了一些工作的react-google-charts ,但似乎缺少Google Charts的许多API,或者至少没有记载。 I'm also a little shy to use something in production that NPM stats show only has ~400 downloads in the last day. 我也很不愿意在生产中使用NPM统计数据显示,最后一天下载的内容只有约400次。

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. 但是我无法在NPM上单独找到Google图表,也无法像我最初期望的那样简单地import Charts from 'google-charts'

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 '???' 1)我该怎么做2)如果可能的话,如何将其包含在诸如import { Line } from '???'类的反应组件中

Use Webpack externals 使用Webpack 外部
By defining a library as external webpack simply export the global symbol for the library, much like (say for jQuery) 通过将一个库定义为external Webpack,只需导出该库的全局符号,就像(对于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 Charts主页添加<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>或更新的URL

  2. In your webpack configuration add: 在您的webpack配置中添加:

     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. 对于ReactJS部分,您需要某种方式来通过使用refs或其他方式来获取脚本中的本机DOM元素。

PS I am not a react guy so maybe someone with react background may help PS:我不是一个有反应的人,所以也许有反应背景的人可能会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM