How to add global functions in Laravel webpack.mix.js?
Asked Answered
B

3

5

I am using Laravel mix to compile my assets and combining them into single file. I created a new js file and wrote some methods in this. I combined this file with app.js file. From my blade file when i try to call those methods i get an error function not defined . I am unable to access those methods.

Please help me out to call those methods.

Laravel Mix code

mix.js([ 'js/app.js',
         'js/custom.js'
        ], 'public/js'),
.....

Custom.js

function test(){
  alert('test')
}

test.blade.php

<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">
    test();
</script>

Error : test is not defined

Budgie answered 4/7, 2018 at 13:47 Comment(4)
Is app.js included before you try to use test();?Domingo
Yes, When i view the source code for app.js, The method exist in app.js at very bottom of app.js. Other events are working but function is not accessible.Budgie
Are you including the file above test()? I don't see <script src="app.js"></script> anywhere in test.blade.phpDomingo
Actually it is added in test.blade.php but i forgot to inform you. Now post updated.Budgie
C
9

Just assign it to window. So in your Custom.js

window.test = function(){
  alert('test')
}

and use it in your test.blade.php:

<script type="text/javascript">
    window.test();
</script>
Conditional answered 25/10, 2018 at 20:9 Comment(1)
This doesn't work for me. I am using laravel 8.75. I get window.test() is undefined.Peripatetic
C
3

Try this:

custom.js

function test(){
    alert('test')
}

export { test };

app.js

...
import { test } from './custom.js';
Cabby answered 21/7, 2018 at 21:50 Comment(0)
E
0

Rather than just concatenating the new file onto the end of the app.js a cleaner approach (imho) is to leave your webpack.mix.js untouched.

Create your custom.js file in resources/assets/js and simply add require('./custom'); at the bottom of resources/assets/js/app.js

This will then be required as part of the rest of the build process.

Exurbia answered 4/7, 2018 at 19:41 Comment(1)
"This is not working" is not helpful. If you want assistance you need to provide as much information as possible. I've done exactly what I suggested above in 3 projects in the last month without any issues.Exurbia

© 2022 - 2024 — McMap. All rights reserved.