I collect all JS files in webpack.

function DetailClass() { this.add = function() { //something... } } var Detail = new DetailClass(); 

After building into 1 file, I try to start the function via HTML:

 <div onclick="Detail.add();">Добавить</div> 

But nothing works. Writes Detail is not defined.

  • as you load js show the code - L. Vadim
  • <script src="{{ URL::asset('js/all.js') }}" type="text/javascript"></script> As I use Laravel. The point is not in connecting the file, but in the fact that after compilation, the webpack wraps the functions in eval () and the scope changes, respectively, I cannot access globally. I tried to solve the problem by declaring the library name in weback.config.js, but did not help. - Detryer
  • and if you write in the console Detail.add () - L. Vadim
  • @ L.Vadim, it will give an error, of course, because there is no global detail variable. The problem is clear in general, then everyone who tried to translate Legacy code to the webpack came across it, and now I will describe the solution. - Duck Learns to Take Cover

1 answer 1

Attention, the answer is relevant for webpack 1 and not for the webpack 2 released a couple of weeks ago. The same principles are likely to remain there, but the API is slightly different.

Through your html, you access Detail as a global variable.

You have it global and it was apparently because var Detail = new DetailClass(); performed at the level of the whole document.

Webpack also expects that the modules that you slip him - real modules, without side effects. Therefore, it calmly wraps everything in the closure and the Detail variable is no longer global and is no longer visible from the global context in which the inline handler works.

What to do?
1. Simple dirty way.
There was a global variable, global one and leave it.

 window.Detail = new DetailClass(); 

Well, of course, this code needs to be executed earlier, than to call Detail from html.
In your code, it will most likely go like this, because I doubt that your application structure is well organized.

2. The correct way.
Carefully read the documentation section that deals with working with legacy code that is not modulated, and choose the method that is right for you (imports-loader / exports-loader / ProvidePlugin)

But if you directly have such a piece of html markup with an inline handler, and it is not created by any template / js code, then these methods are hardly suitable for you because they are intended for cases when the client part is organized normally =)

  • It's not so much the presence or absence of side effects, as in the very concept of "module". All module variables are local by construction. - Pavel Mayorov