Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use laravel mix define global javascript function

I already have a function in resources/assets/js/common/utils.js

'use strict'

function test(){
   console.log('test');
}

How can I define utils.js as a global file and to be use any where? Thanks for read my question!

like image 659
Trần Quốc Vũ Avatar asked Mar 29 '26 02:03

Trần Quốc Vũ


1 Answers

If you need to use it outside of your bundled JavaScript files you can attach it to the window object

window.test = function () {
  console.log('test');
}

Which you can then use in other files, such as your blade template files as

window.test();

Or if you want to use it within your bundled JavaScript files you can import it as a module

// test.js
export default function test() {
    console.log('test');
}

// other.js
import test from 'test.js';

test();

As long as you are compiling your files with Laravel Mix as described here in the docs.

like image 153
Josh Avatar answered Mar 31 '26 04:03

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!