How to define a default export with vanilla JS ES modules
Yesterday, we learned how to use import
and export
with ES modules. Today, we’re going to learn about another export
pattern: default exports.
Let’s dig in.
A quick recap
In our simple helper library yesterday, we exported an object of helper functions, like this.
export {add, subtract};
Alternatively, we could also add the export
operator before each function, like this.
export var add = function (num1, num2) {
return num1 + num2;
};
When we go to use any of those methods, we import them as keys in an object, like this.
import {add, subtract} from './modules/helpers.js';
This makes sense in a script with several exported functions, but what about when there’s only one?
The default
export
Let’s imagine that instead of several helper functions, we had a script with just one: getTheAnswer()
, that returns 42
.
var getTheAnswer = function () {
return 42;
};
We could export
it the way we always have, like this.
export {getTheAnswer};
But, we can also export it as a default export, like this.
export default getTheAnswer;
With this approach, we can skip the object when importing it into our script.
import getTheAnswer from './modules/helpers.js';
// Get the answer
var answer = getTheAnswer();
// Tell them the total
alert('The answer is ' + answer);
Exporting multiple functions with a default
What if you have a script with multiple functions, but you want one of them to be the default, with the rest as optional exports?
var getTheAnswer = function () {
return 42;
};
var add = function (num1, num2) {
return num1 + num2;
};
var subtract = function (num1, num2) {
return num1 - num2;
};
In this case, you would export an object, but add as default
to the default export.
export {getTheAnswer as default, add, subtract};
When you go to import, you can import just the default, like this.
import getTheAnswer from './modules/helpers.js';
Or, you can import just the others, like this.
import {add, subtract} from './modules/helpers.js';
Or, you can import both, like this.
import getTheAnswer, {add, subtract} from './modules/helpers-alt.js';
Some demos
You can download demos from what we talked about today on GitHub.
Don’t forget that you’ll need to run a server for these to work, either in command line or using a GUI tool like MAMP.
In a future lesson, we’ll be looking at how to add a build step.