Understanding Default and Named Exports
There are two ways to import other modules in a file and they are different depending on how the module has been exported. Be sure to read about modules if you haven't come across them yet or how they fit into the modern JavaScript ecosystem.
Default
If a JavaScript file export
s a function
, class
, React component
etc using default
then this gets exported and treated as the module itself. Default exports are great for libraries like React, because it allows consumers to import a single API.
Note
A module can only have oneexport default
statement, but it can have many named exports. These are covered in the next section.
Here's what a default export looks like:
const prng = () => {
// generate a random number by monitoring
// spin changes in quantum particles, or
// something like that.
};
export default prng;
The pseudo-random number generator can now be imported into another module and used just like any other function:
import prng from "./utilities/prng";
Notice there are no curly braces surrounding the import, that's because the module itself is being imported.
It's also perfectly valid to change the name of the module on import to something different:
import getMeARandomNumber from "./utilities/prng";
The module can then be called by it's new name:
getMeARandomNumber();
Sometimes this can reduce complexity when working with long module names or things that are regularly shortened, like accessibility
→ a11y
.
Named
As mentioned above, a module can have any number of named exports. These export a specific portion of the module so that they can be imported elsewhere in a more finely grained manner:
export const prng = () => {
// ...
};
export const something = () => {
// ...
};
These are then imported by wrapping curly braces around the named exports from the module:
import { prng, something } from "./utilities/utilities";
Also, just like default, you can change the name of a named import, but the syntax is slightly different:
import { prng as getMeARandomNumber } from "./utilities/utilities";
Using the above, prng
can now be called using getMeARandomNumber
.
You may have already seen libraries like React use both default and named exports in a module. This is less common, but does provide a way to cover most bases with the default and others can be imported separately as the need arises:
import React, { Suspense } from "react";
I lied
At the start of the post, I mentioned that there were two ways of importing modules. I lied: there is another.
The import()
function from the SystemJS package returns a promise when the module at the specified is imported and ready for use:
if (clientHasQuantumSubscription) {
System.import('./utilities/prng').then((prng) => {
// use prng
});
}
It's not used nearly as much as the ones above (I've never used it), but allows you to do things like conditional imports.