This one had me pulling my hair out the other day. I was using Laravel, adding a javascript function to the app.js file ( also tried using require in app.js and pulling in my function ). Laravel uses Laravel Mix which is a wrapper for webpack.
Yet with either approach I was getting the javascript error:
Uncaught ReferenceError: testing_helloworld is not defined
It seemed to be working ( had npm run watch , compiling it and doing a view source I could see the function in my javascript app.js file ).
My function source code looked like this:
function testing_helloworld(){ alert(' why is this not working !!!! '); }
It seems webpack wraps this in IIFE (see details on mozilla site )
This has the effect of wrapping it in its own scope ( and not in the global scope ).
So to put it in the global scope, so you can call it anywhere, you need to pop the function onto a global such as Window as below:
window.testing_helloworld = function() { alert(' a-ha it works ! '); }
I’d have read through my app.js file , but it was massive and would have taken me awhile to find this I think ! Hope this helps someone else with Laravel Mix, Webpack and adding your own javascript functions.
While coming across many StackOverflow posts during my search, I did not come across the one you referenced. I spent half my day with the same problem you had. Thank you for this.
It sure doesn’t help that Laravel Mix and Webpack are only items I’ve had to deal with because I use Laravel. If I knew how to use Laravel without dealing with these 2 tools I’m not super familiar with, I’d have gone that route.
glad you found the post useful David.
I remember that problem made me pull a few hairs out !