我正在尝试在NodeJS上使用ChartJS,但是它不起作用。我安装了npm install chart.js --save
,并按如下所示创建了最简单的测试,但是显示了错误Chart is not defined
。我已经尝试将文件“ chart.js”复制到同一目录,我已经尝试指向node_modules/chart.js/....
目录,但是我无法使其工作。我也无法指向文件https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js
,因为系统应该可以“独立运行”
<html>
<head>
<script src="chart.js"></script>
</head>
<body>
<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
var chrt = document.getElementById("mycanvas").getContext("2d");
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.8)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
};
var myFirstChart = new Chart(chrt).Bar(data);
</script>
</body>
</html>
怎么了?
导入图表库的方式没有错。它应该以这种方式工作[[(只要一切都正确设置):
...
<script src="chart.js"></script>
...
但是,由于要使用构造表的语法,可能会发生实际的问题。,但是您使用的是旧语法(是针对v1.x),同时创建图表。这里是在Chart.js 2.6版中创建图表的正确语法:[当您使用
npm install chart.js --save
安装Chart.js模块时,它会安装Chart.js的最新版本(当前为2.6)
...
var chrt = document.getElementById("mycanvas").getContext("2d");
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(220,220,220,0.8)",
borderColor: "rgba(220,220,220,0.8)",
hoverBackgroundColor: "rgba(220,220,220,0.75)",
hoverBorderColor: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
};
var myFirstChart = new Chart(chrt, {
type: 'bar',
data: data
});
...
npm install chart.js
,然后在与index.html
相同级别上创建node_modules
。然后我像这样导入它。<script src="./node_modules/chart.js/dist/Chart.js"></script>
工作正常,请尝试,如果无法正常工作,请提供更多详细信息。
示例:
index.html
<script src="/bootstrap.min.js"></script>
app.js
app.get('/bootstrap.min.js', function(req, res) { res.sendFile(__dirname + '/node_modules/bootstrap/dist/bootstrap.min.js'); });
有关更多详细信息,请参见@ jfriend00 How to include scripts located inside the node_modules folder?提供的绝佳答案