Chartjs-ChartJS on NodeJS: error Chart is not defined

2👍

There is nothing wrong with the way you are importing the chart library. It should work this way (as long as everything is set correctly) :

...
<script src="chart.js"></script>
...

However, the actual issue might occur, because of the syntax you are using to construct the chart.

When you install Chart.js module using npm install chart.js --save, it installs the latest version of Chart.js (which is at the moment 2.6), but you are using old syntax (which is for v1.x) while creating the chart.

Here is the correct syntax for creating a chart in Chart.js version 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
});
...

0👍

I’m not so sure that you are using framework or not but I try npm install chart.js then create index.html in the same level with node_modules. Then I import it like this.

<script src="./node_modules/chart.js/dist/Chart.js"></script>

Work fine ,please try and if it not work please provide some more details.

0👍

You might want to avoid referencing your modules in your front-end files. Instead consider creating a route for your module files and then reference the route in your front-end files.

Example:

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');
});

For more specifics please see this great answer courtesy of @jfriend00 How to include scripts located inside the node_modules folder?

Leave a comment