Proper Method to Import Functions from another file

What I am trying to do is split a file that is getting rather large. I am using blaze so I have my main js file with all the blaze code in it, then I wanted to take a separate file for all the functions related to that page.

I wanted to import those functions into the blaze file so that they are callable from there.

To do this do I only need to create the separate file with the functions and just use an import statement to bring it into the main blaze file?

Do I need to do something special to the functions file for it to work?

Did some googling but not sure I know exactly what I am looking for. Any help is apprecated.

Your functions file should then be something like this:

export const someFunction = () => {
  // Do something
};

export const someOtherFunction = () => {
  // Do something else
};

However, its a good practice to keep one function per file. That makes that you can import them individually and each function might have its own dependencies too…

To make it convenient you can do something like this:

functions.js

import someFunction from './functions/someFunction';
import someOtherFunction from './functions/someOtherFunction';

export { someFunction, someOtherFunction };

Then in your function files you can do so called default exports:

./functions/someFunction.js

export default () => {
  // Do something
}

./functions/someOtherFunction.js

export default () => {
  // Do something else
}

Good luck :smiley:

This makes some sense thank you.

Just so I have everything straight using the one file per function and importing them into an import file and exporting them all. What does the import function on the blaze file look like to handle these?

Ok I think I figured this out. I want to post it here in case I am wrong and can adjust my code after.

On the blaze main js file I would import the import file as follows:

import {someFunction} from './functions/functionsMaster';

If this is wrong please let me know.

It would look like this

import {someFunction, someOtherFunction} from './functions'

You can with this new setup also import then individually (which is my preference)

import someFunction from './functions/someFunction';
import someOtherFunction from './functions/someOtherFunction';

The bottom one would be a better practice since it will become easier to keep your code ‘loosely coupled’, meaning different parts of your code have less the minimum amount of dependencies. Now you would be able to for example replace one of your functions with an NPM equivalent or vice versa.

Thank you for the help. This was always something that seems out of my scope.(Just learning still) But this seems clear and I was able to get it up and running with my sample code easily enough. This will make my project files a lot more readable now and easier to follow.

1 Like