Unable to access variables after compiling webpack

I cannot access variables after compiling webpack. I need this because I use this variable to call a function in onclick.

the code is similar to

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

var Detail = new DetailClass();
Run codeHide result

Webpack including this code in eval ()

And in HTML I call it like

<div onclick="Detail.add();">Add</div>
Run codeHide result
+4
source share
2 answers

You should not associate such events!

Are you using some kind of framework like React or even jQuery? If you use the latter, for example, link like this (in JS, not HTML):

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

If you do not, follow these steps:

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

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

window.Detail = Detail;
+2

- output.library output.libraryTarget.

: https://webpack.imtqy.com/docs/configuration.html#output-library

:

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

:

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

Source: https://habr.com/ru/post/1667776/


All Articles