I'm using Laravel 5 Boilerplate that comes with some structure already done.
I want to call a simple JavaScript method from the blade. Here's what I did:
1) Created file called test123.js
content of test123.js
:
function test123() {
$(document).ready(function () {
console.log('hello from test123');
});
}
2) I opened the existing app.js
and added:
import './test123';
3) I called npm dev run
- all green, all OK.
4) In blade index.blade.php
I typed:
@push('after-scripts')
<script>
test123();
</script>
@endpush
I went to compiled file:
<script src="http://foo.local/js/backend.js?id=8dbe74e012c3122422da"></script>
My method is there:
however it's not visible.
I guess it's about scopes? I don't want to make it window.test123. Should I? I just want define good old JS / jQuery method and invoke it only when needed in specific templates.
"Modern" JS is not my strong point as I find it very convoluted. I haven't touched default webpack.mix.js
.
mix.setPublicPath('public');
mix.sass('resources/sass/frontend/app.scss', 'css/frontend.css')
.sass('resources/sass/backend/app.scss', 'css/backend.css')
.js('resources/js/frontend/app.js', 'js/frontend.js')
.js([
'resources/js/backend/before.js',
'resources/js/backend/app.js',
'resources/js/backend/after.js'
], 'js/backend.js')
.extract([
'jquery',
'bootstrap',
'popper.js/dist/umd/popper',
'axios',
'sweetalert2',
'lodash',
'@fortawesome/fontawesome-svg-core',
'@fortawesome/free-brands-svg-icons',
'@fortawesome/free-regular-svg-icons',
'@fortawesome/free-solid-svg-icons'
]);
Please help me to achieve this simple thing. I know the solution probably is not difficult but I don't know what to do…
Thank you.
Edit 1: I almost forgot. Here's the Boilerplate structure:
Edit 2: User brk requested some more screenshots:
Try exporting the function explicitly:
export function test123() {...}
and later import it:
import 'test123' from './test123';
You can try do this with require.js
//declare fn test123
test123(){ ...do something}
module.exports.test123 = test123;
and then
let test123 = require('./test123');
Here you can find more information about using require.js in browser with jquery https://requirejs.org/docs/jquery.html