In this article, we’ll explore various methods of including external JavaScript module files into your main or controller files. With ES6, we’ve got an excellent feature: the ability to export and import modules. This makes your code more organized, readable, and modular.
Let’s dive into the topic.
Exporting Functions
In a JS file, when you write multiple functions and want to use them in another file, you can use the keyword export. If you want to export more than one function, you can do it like this:
export { function1, function2, function3 }
Example:
You have a calculation.js file that performs basic math operations. To export these functions:
const sub = (a, b) => {
return a - b;
}
const add = (a, b) => {
return a + b;
}
export { sub, add };
Now, if you have only one function to export, there’s a special way to do that — using export default
const multiply = (a, b) => {
return a * b;
}
export default multiply;
Importing Functions
Once your modules are neatly organized, it’s time to import them into your main file or controller.
Named Import (Multiple Functions)
To import the named exports from calculation.js, use the following
import { sub, add } from './modules/calculation.js';
console.log(sub(10, 20));
Note: Adjust the path based on your folder structure. Use relative paths (./, ../) instead of absolute ones.
Default Import
When you've exported a single function as default:
import multiply from './modules/calculation.js';
console.log(multiply(20, 3));
Import with Namespace
import * as calc from './modules/calculation.js';
console.log(calc.add(5, 10));
console.log(calc.sub(20, 5));
This way, you refer to all your functions through the calc object.
Combining Multiple Modules
Let’s say you have 3–4 module files, and you don’t want to import each one individually in every file. The cleanest way is to combine all exports into a single file, then import from that intermediate file wherever needed.
Combine.js
export * from './modules/calc.js';
export * from './modules/names.js';
export { default as seasons } from './modules/seasons.js';
Then, in your controller or main JS file:
import * as combine from './modules/Combine.js';
console.log(combine.multiply(22, 8));
console.log(combine.seasons.whichSeason());
In this setup, Combine.js acts as a bridge between your modules and your main file.
Final Thoughts
That’s it for today! I’ll be back soon with another article. I hope this guide helped clarify how export and import work in JavaScript. Feel free to share your thoughts or questions in the comments.
Thanks for reading — cheers! 🙌
Top comments (0)