Laravel MIX, how to use single function in multiple files

Viewed 2017

I have three files:

  • my_function.js
  • scripts_1.js
  • scripts_2.js

my_function.js

function myFunction() {
  console.log('my function');
}

How can I use this function in both of my files scripts_1.js and scripts_2.js? I use these two in users.js as:

require('scripts_1');
require('scripts_2');

and in admins.js I use only one:

require('scripts_2');

Later in my webpack.mix.js I compile the users and admin files to two separate minified js files.

If I just use the require('my_function') in my scripts_1 and scripts_2 files this doesn't work (probably the myFunction() is not in the same scope).

However I can make this work if I attach my function to the window variable so that the my_function looks like this now:

window.myFunction = function() { ... }

At this point I don't even have to require it in any of the scripts_1 and scripts_2 files (but I do in my users.js and admin.js files) but this feels wrong somehow.

tldr;

I'd like to know how to define a helper js function that I can reuse in multiple other js files by using Laravel MIX.

1 Answers

Are you exporting myFunction?

In node, you can do

module.exports = {
   myFunction: function () {
     console.log('my function');
   }
}

With webpack and friends, you can simply

export function myFunction() {
  console.log('my function');
}

Then you can import and use the function

const someName = require('my_function.js')

someName.myFunction()

Exporting the function you are telling that the module (the file in that case), has that function. And when you import the module you will be able to use that funcion, it's some type of public/private behavior, exported functions/objects,... are public to other modules, non exported functions/objects/... are private.

To use a exported function, first you need to import the module in every file you want to use it (require('themodule')). Instead, using window, you are attaching in the global object window a new property, so once you have imported in some file the module you can use window.myFunction in any file. The last is not desirable.

Here you have the differents types of modules that javascript has.

Related