Home > OS >  Cannot access variables defined in webpack after build from client
Cannot access variables defined in webpack after build from client

Time:11-28

This may be a novice question, however after researching other questions on the platform and delving through the Webpack documentation I have seen many ways people have attempted this. I have seen nothing really which I can take to apply to my problem.

I wish to use Chart.js using a bundler (Webpack). Creating this file I store the instance in a variable. See the below code snippets to follow along.

src/index.js

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],
        }]
    }
})

webpack.config.js

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index.js',
    }
}

index.ejs

<script src="../dist/index.js"></script>

The chart loads no problem after building using the webpack command. The issue I am facing is that I would assume that I could access the instance of this chart in my console as I wish to do some updating of data after initialization of the chart.

I would expect to be able to access the variable myFirstChart as I would if Chart.js was a CDN or loaded directly.

Is this something that I have maybe overlooked within the documentation of either Chart.js or Webpack 5?

CodePudding user response:

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).

  • Related