Svitavsky
Svitavsky

Reputation: 291

Can't access variables after webpack compilation

I can't access variables after webpack compilation. I need it, because i'm using this variable to call function in onclick.

code is like

function DetailClass() {
  this.add = function() {
    console.log(1);
    }
}

var Detail = new DetailClass();

Webpack including this code into eval()

And in HTML i call it like

<div onclick="Detail.add();">Add</div>

Upvotes: 4

Views: 1233

Answers (2)

Luan Nico
Luan Nico

Reputation: 5917

You shouldn't bind the events like that!

Are you using some framwork, like React or even jQuery? If you are using the latest, for instance, bind like so (in the JS, not HTML):

$('#your-id').on('click', () => Detail.add());

If you are not, bind like this:

document.getElementById('your-id').onclick = () => Detail.add();

However, if this is an exception and you really want to export something, you can set that to the window object:

window.Detail = Detail;

Upvotes: 2

DDRamone
DDRamone

Reputation: 1158

In your webpack configuration you have to specify output.library and output.libraryTarget.

Here's a guide: https://webpack.github.io/docs/configuration.html#output-library

For following configuration:

...
output:{
  ...
  library: 'MyLib',
  libraryTarget: 'var'
}
...

You will be able to use it like:

<div onclick="MyLib.Detail.add();">Add</div>

Upvotes: 6

Related Questions