First , code in resources/js/app.js
function button1Clicked(){
  console.log('Button 1 is clicked');
}
Second , code in testing.blade.php
<!DOCTYPE html>
<html>
<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Testing</title>
</head>
<body>
  <button onclick="button1Clicked()">Button 1</button>
  <button onclick="button2Clicked()">Button 2</button>
  <script type="text/javascript" src="{!! asset('js/app.js') !!}"></script>
  <script type="text/javascript">
    function button2Clicked(){
      console.log('Button 2 is clicked');
    }
  </script>
</body>
</html>
After npm run dev and testing in localhost

As a result, JavaScript function button1Clicked() in resources/js/app.js is not defined. but the function button2Clicked() in testing.blade.php can be defined.
Is it a bug from Laravel Mix or I did some mistakes
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);
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With