JavaScript function is not defined with Laravel Mix

Solution 1:

I had the same problem as you.

It turned out that when Laravel-mix, aka Webpack, compile the js, it wraps our function in a closure.

For example, when we define a function like this

function setlocale(code) {
     console.log(code);
}

Webpack will generate into

(function(module, exports, __webpack_require__) {

     function setlocale(code) {
         console.log(code);
     }

});

That's why we can access the variables or functions inside that closure, but we cannot from the outside as it limits our scope.

A simple solution is setting our function into window variable, which is a global variable.

window.setlocale = function (code) {
    console.log(code);
}

Solution 2:

update the code in resources/js/app.js as below-

button1Clicked = function(){
    console.log('Button 1 is clicked');
};

then it will be available for global scope.