[Chartjs]-How do I import chartjs as an es6 module?

2๐Ÿ‘

โœ…

Iโ€™m pretty new to the whole JS module stuff but had the exact same problem.
I got it working using the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Load Chart.js as ES2015 module</title>
    <script type="module">
      import 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js'
      
      const canvas = document.getElementById("chart");
      let chart = new Chart(canvas, {
        type: "line",
        data: {
          labels: ["1", "2", "3", "4", "5"],
          datasets: [{
            label: "Series 1",
            data: [1, 2, 3, 2, 1]
          }]
        }
      });
    </script>
  </head>
  <body>
    <canvas id="chart"></canvas>
  </body>
</html>

The problem Iโ€™m facing now is that the TypeScript compiler gives me the following error:

'Chart' refers to a UMD global, but the current file is a module. Consider adding an import instead.

But this is not an issue if you are not using TypeScript and the JS code above works in browsers.

Leave a comment