chartjs / chartjs-plugin-datalabels

Chart.js plugin to display labels on data elements
https://chartjs-plugin-datalabels.netlify.app
MIT License
863 stars 460 forks source link

How to load via Laravel Mix? #280

Closed Synchro closed 2 years ago

Synchro commented 2 years ago

I'm trying to get this plugin to work, but really getting nowhere. I have installed it from npm, and configured Laravel mix (webpack front-end) to bundle chart.js and this plugin into a single JS file:

mix.js(
    [
        'node_modules/chart.js/dist/chart.js',
        'node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js'
    ],
    'public/js/chart.js'
);

I can see that this does indeed include the source of both packages in the target file. I then load that into my page with a script tag. I can create Chart instances with no problems (despite having no import statement relating to it) , but I just can't seem to get the plugin to work at all. The registration syntax in the docs doesn't work for me:

import {ChartDataLabels} from 'chartjs-plugin-datalabels';

SyntaxError: Unexpected token '{'. import call expects exactly one argument.

If I remove the {}, I get:

SyntaxError: Unexpected identifier 'ChartDataLabels'. import call expects exactly one argument.

If I do neither of those, I just get a ReferenceError: Can't find variable: ChartDataLabels when I try to use the plugin.

I'm sure I must be be missing something very basic, but I don't know what.

LeeLenaleee commented 2 years ago

Not sure if it might work but you can try to import everything and see if the ChartDataLabels is present in there and use it that way. So it will look something like this:

import * as datalabels from 'chartjs-plugin-datalabels';

Chart.register(datalabels.ChartDataLabels);
Synchro commented 2 years ago

Thanks for replying. Unfortunately this fails in a similar way:

import * as datalabels from 'chartjs-plugin-datalabels';

SyntaxError: Unexpected token '*'. import call expects exactly one argument.

That was in Safari; Chrome gives a slightly more useful error message:

Uncaught SyntaxError: Cannot use import statement outside a module

So I guess I'm not using a module?

FWIW, this is my combined JS file (it's in dev mode so not minified).

Synchro commented 2 years ago

When I look at the generated source file, I can see that webpack has stripped out the definition of ChartDataLabels, so I have no way of registering it or otherwise getting a handle on it. While this explains some of the errors, it doesn't get me any closer to figuring out how to load this plugin!