where is your app.js loaded from, try putting it at the end of <body>
Function not defined
I have this simple function in my app.js:
function myTest() {
console.log('test');
}
I get a function not defined error when I call it.
<button onclick="myTest()">Button</button>
But it works when I place it right under the <script src="{{ asset('js/app.js') }}"></script>
Is there a way to fix this?
Here is my webpack:
const mix = require('laravel-mix');
mix
.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
mix.webpackConfig({
node: {
fs: "empty"
}
});
There are two ways to accomplish what you're trying to achieve with your bundled Webpack JS.
First Method
The first method, which is the recommended way, would be to add library and libraryTarget to your Webpack export settings:
mix.webpackConfig({
output: {
library: 'libraryName',
libraryTarget: 'umd',
umdNamedDefine: true, // optional
globalObject: 'this' // optional
}
})
library is, of course, your library name, libraryTarget is the type of library output you will get. You have multiple options, but the most common are var (available when loading a script within a script tag) and umd, which is compatible with every support forms (ES6, AMD, CommonJS and var). umdNamedDefine is only pertinent when using umd target and AMD syntax, but AMD syntax isn't common anymore so... As for globalObject, it is once again only required (if I remember correctly) when the library target is umd. It represents the global object to bind to and by default is is 'window', which causes issues with umd.
Then, at the bottom of your JS file(s), you'll need to export functions that you want to make available:
const yourFunction = function () {
// ...
}
module.exports = {
yourFunction
}
And to finish, to use it in your HTML/PHP file:
libraryName.yourFunction()
Second method
The second method is the simple solution. You simply need to bind your function to the window:
// In your JS file
window.myFunction = function() {
// ...
}
// In your HTML/PHP file
window.myFunction()
Please or to participate in this conversation.