javascriptchart.jstreemap

chartjs-treemap not registering in chart.js


I'm trying to extend a working implementation (I'm using line, pie, bar and scatter chart types with no problem) of Chart.js with the treemap extension. I'm using vanilla JavaScript.

// The ellipsis is just shorthand for the various elements I'm using
import {Chart, ..., Tooltip} from 'https://cdn.jsdelivr.net/npm/chart.js@4.5.1/+esm';

import {TreemapController, TreemapElement} from 'https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@3.1.0/+esm';

Chart.register(..., Tooltip);

Chart.register(TreemapController, TreemapElement);

On page load I get the following in the console:

Unable to register the treemap positioner because tooltip plugin is not registered

Which is slightly odd in that tooltips work fine in my existing charts.

If I try to instantiate a treemap chart then I get:

Error: "treemap" is not a registered controller.

I'm obviously doing something wrong but equally as obviously I can't see what it is.


Solution

  • The jsDeliver esm bundle for chartjs-chart-treemap@3.1.0 is currently linked to a specific version of chart.js, 4.4.4. The version of chart.js that is used can be read in the first import line of the imported module, https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@3.1.0/+esm, otherwise minified and unreadable.

    The module imports the specified version of chart.js, but it doesn't export it, so you'll have to explicitly import chart.js too. However, if you import another version, you'll end up with two registries, one for the chart.js version you imported, e.g., 4.5.1 and one for 4.4.4, used by the treemap plugin, where it can't find anything it requires dynamically. The only solution, if module imports from jsDeliver are to be used, is to import the version of chart.js needed by the plugin:

    import {Chart, ..., Tooltip} from 'https://cdn.jsdelivr.net/npm/chart.js@4.4.4/+esm';
    

    (here's an example working).

    That is highly problematic if other plugins are to be used, that are tied with different versions of chart.js (although it's possible that several current useful modules are tied to the same version). Then, it is possible that the jsDeliver bundles will be updated, so a newer version than 4.4.4 will be required for compatibility with chartjs-chart-treemap@3.1.0 in the future, making your code break without notice.

    The alternative is to use one of the solutions recommended by chart.js docs (see Getting Started and Installation). Local copies of the modules and custom bundling is the solution that gives you the best level of control, while non-module use of CDNs makes sense, as tree-shaking is not useful when CDNs are used.