Chartjs-Cannot access variables defined in webpack after build from client

1👍

The whole point of webpack is to process modules, and the whole point of modules is to not pollute the global name space. If another file of JS code needs access to a variable, export it where it is created, and import it in that other file.

Any variables defined in modules are module-scoped only; it is widely considered bad practice to make use of the global namespace at all.

If you absolutely need that (and you’re most probably doing it wrong if that is the case), add window.myFirstChart = myFirstChart; in your index.js file:

import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

const myFirstChart = new Chart("test", {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
        }]
    }
})
window.myFirstChart = myFirstChart;

Any variable you need to be available globally you explicitly need to publish by attaching it to the global window object (which is where the browser looks them up unless they’re defined anywhere more local as to where you’re trying to access it).

Leave a comment