如何在Laravel中安装Chart.js?

4

我想在我的 Laravel 项目中安装 Chart.js。使用 npm install,为 Webpack 进行配置,并查看我的 index 页面上的一些 Chart.js 示例。第一次尝试时,在浏览器中出现了以下错误。也许我没有正确配置 webpack?

Uncaught ReferenceError: Chart is not defined at (index):134

于是我复制并粘贴了在 Chart.js 文档中找到的这个 require。

require(['path/to/chartjs/dist/Chart.min.js'], function(Chart){
    var myChart = new Chart(ctx, {...});
});

在执行 npm run dev 命令时,我遇到了这个错误。

ERROR in ./resources/js/app.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: /home/sa/laravelproject/resources/js/app.js: Unexpected token (37:37)

35 | 36 | require(['path/to/chartjs/dist/Chart.min.js'], function(Chart){

37 | var myChart = new Chart(ctx, {...}); | ^ 38 | });


{...} 表示您需要在那里放置选项... 尝试使用:var myChart = new Chart(ctx, {}); - koalaok
你不能使用这个库吗:https://vue-chartjs.org/guide/#introduction? - Erubiel
5个回答

11

在命令行中运行以下命令:

npm install chart.js
在 webpack.mix.js 文件中添加这一行:
mix.copy('node_modules/chart.js/dist/chart.js', 'public/chart.js/chart.js');

然后从命令行运行以下命令:

npm run dev

你想在哪个刀片上显示图表:

<script src="{{ asset('chart.js/chart.js') }}"></script>
<canvas id="myChart" width="500" height="200"></canvas>
<script>
  var ctx = document.getElementById('myChart').getContext('2d');
  var myChart = new Chart(ctx, { 
  ...
  }
</script>

对于像4这样的较新版本,@ardhiarah下面的答案会更好用。 - Magmatic

3
您可以在app.js中注册一个全局的Chart变量,如下所示:
// Chart JS
import Chart from 'chart.js/auto';
window.Chart = Chart;

然后你可以在视图或其他JS文件中使用它,方法是 new Chart(....)


我遇到了问题。我尝试了你的答案,编译后在浏览器中运行时出现了错误“Invalid scale configuration for scale: xAxes”和“Invalid scale configuration for scale: yAxes”,请帮助我。 - Harsh Patel
1
非常感谢!将它添加到窗口对象中是最好的选择。我已经为此苦恼了一个小时 :) - JoshP

1

@Magmatic的回答很接近。

对于像我使用的v4.x这样的新版本,请稍作修改:

mix.copy('node_modules/chart.js/dist/chart.umd.js', 'public/js/chart.js');

添加另一个来隐藏错误提示:

mix.copy('node_modules/chart.js/dist/chart.umd.js.map', 'public/js/chart.umd.js.map'); mix.copy('node_modules/chart.js/dist/helpers.js.map', 'public/js/helpers.segment.js.map');


我可以确认这适用于版本4。 - Magmatic

1
我是一个有用的助手,可以为您进行翻译。以下是您需要翻译的内容:

我遇到了一些问题。

首先,我无法通过NPM引入库。我已经安装了它,然后执行了"npm run dev"。但是当我在应用程序中调用它时,它会显示以下信息:

1:2573 Uncaught ReferenceError: Chart is not defined
    at 1:2573

如果我从CDN调用它,它会与VUE或Bootstrap的某些东西发生冲突。因为它不起作用。除非我从app.blade.php中的行中删除“defer”单词:
    <script src="{{ asset('js/app.js') }}" defer></script>

但是,只能通过CDN调用Charts.Js。无法从NPM中获取。

希望有人遇到了同样的问题。谢谢。 Hernán。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接