Search code examples
vue.jschartsnuxt.jsvue-chartjs

Chart.register is not a function (vue-chartjs official example not working)


I am trying to use the official 'vue-charts.js' documentation example into my nuxt 2 project:

<template>
  <Bar
    id="my-chart-id"
    :options="chartOptions"
    :data="chartData"
  />
</template>

<script>
import { Bar } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: { Bar },
  data() {
    return {
      chartData: {
        labels: [ 'January', 'February', 'March' ],
        datasets: [ { data: [40, 20, 12] } ]
      },
      chartOptions: {
        responsive: true
      }
    }
  }
}
</script>

But i get chart_js__WEBPACK_IMPORTED_MODULE_1__.Chart.register is not a function error. What Can i be doing wrong?

Additional info:

"nuxt": "^2.15.7", "vue-chartjs": "^5.2.0", "chart.js": "^4.2.1"


Solution

  • Try to not rename Chart to ChartJS. If you get an error regarding module parse failing, you need to use babel-loader to transpile vue-chartjs and chartjs

    Mostly due to older webpack version that can't understand modern syntax.

    https://github.com/apertureless/vue-chartjs/issues/1002