chartJS4で”arc” is not a registered element.のエラーが出た話

chartJS4で”arc” is not a registered element.のエラーが出た話

vue-chart.jsのサンプルを試していたら、”arc” is not a registered element. のエラーが出た時の話。

解決までの記録。

実行環境

  • chart.js 4.2.1
  • vue-chartjs 5.2.0
  • vue 3.2.45
  • docker desktop 4.16.2
  • macOS Ventura 13.2

事象

vue-chart.jsのサンプルを見ながら、チャート表示を確認していたところ、

バブルチャート、ドーナツチャート、ラインチャートを表示しようとしたら、以下のエラーが出た。

Uncaught Error: "linear" is not a registered scale.
Uncaught Error: "arc" is not a registered element.
Uncaught Error: "point" is not a registered element.

調査してわかったこと

調査をしてみると、chart.js3はtree-shakeableなので、必要なコントローラーやエレメント、スケールなどの利用するものをインポートする必要があるとのこと。

Chart.js 3 is tree-shakeable, so it is necessary to import and register the controllers, elements, scales and plugins you are going to use.

https://www.chartjs.org/docs/3.3.0/getting-started/integration.html#bundlers-webpack-rollup-etc

Tree shaking とは、モジュールの依存関係を静的に解析して、副作用のない不要なコードを削除する機能のことのようで、必要なモジュールだけ読み込まないといけないようだ。

サンプルソースを見直してみると、
バブルチャートには、PointElementが、
ドーナツチャートには、ArcElementが読み込まれていた。

バーチャートのサンプルをベースにしていたので、インポート部分を変更していなかったことが今回の問題だった。

解決方法

chart.js/autoに変更することで、自動的に依存関係のあるモジュールをインポートしてくれるようだ。
これに変更すると、チャートが正常に表示された。

import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from "chart.js";
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

↓↓↓↓↓↓

import 'chart.js/auto';

StackOverflowに同じ話しがあった。

https://stackoverflow.com/questions/67727603/error-category-is-not-a-registered-scale

実運用では、必要なライブラリだけ限定してインポートした方が良いだろうが、
今回は、chart.js/autoで進めていく。

Web技術カテゴリの最新記事