如何在webpack中使用chart.js

时间:2016-10-25 08:47:11

标签: javascript requirejs webpack

我在webpack中使用chart.js。当在终端中运行webpack时,它可以,但在控制台显示错误:

“未捕获的ReferenceError:未定义图表”

require(['jquery', 'chartjs'], function($, chartjs) {
console.log('aaaaaaaa');

var riceData = {
    labels : ["January","February","March","April","May","June"],
    datasets :
     [
        {
          fillColor : "rgba(172,194,132,0.4)",
          strokeColor : "#ACC26D",
          pointColor : "#fff",
          pointStrokeColor : "#9DB86D",
          data : [203000,15600,99000,25100,30500,24700]
        }
     ]
    }

    var rice = document.getElementById('myChart').getContext('2d');
    new Chart(rice).Line(riceData);
});

2 个答案:

答案 0 :(得分:0)

您将变量名称chartjs提供给require.js的回调,但您尝试在倒数第二行引用Chart的chartjs。您需要做的是决定命名约定:

require(['jquery', 'chartjs'], function($, Chart) {
console.log('aaaaaaaa');

var riceData = {
    labels : ["January","February","March","April","May","June"],
    datasets :
     [
        {
          fillColor : "rgba(172,194,132,0.4)",
          strokeColor : "#ACC26D",
          pointColor : "#fff",
          pointStrokeColor : "#9DB86D",
          data : [203000,15600,99000,25100,30500,24700]
        }
     ]
    }

    var rice = document.getElementById('myChart').getContext('2d');
    new Chart(rice).Line(riceData);
});

答案 1 :(得分:0)

通过将require更改为define来解决问题。您还应该使用npm包管理器。

define(['jquery', 'chartjs'], function($, chartjs) {

var riceData = {
    labels : ["January","February","March","April","May","June"],
    datasets :
     [
        {
          fillColor : "rgba(172,194,132,0.4)",
          strokeColor : "#ACC26D",
          pointColor : "#fff",
          pointStrokeColor : "#9DB86D",
          data : [203000,15600,99000,25100,30500,24700]
        }
     ]
    }

    var rice = document.getElementById('myChart').getContext('2d');
    new Chart(rice).Line(riceData);
});