Import Named Exports
By default, expressions and assignments declared inside a module aren’t available outside of that module.
Here, hype
is only available to other functions inside string-utils.mjs
.
We can expose hype
to other modules by prepending the export
keyword.
hype
is now a named export from the string-utils
module.
Keep in mind that export
-ing something doesn’t mean it is automatically available throughout the codebase. Every export
requires an import
.
Import named exports
Anything one module exports can be imported and used by another module.
The syntax we use to access named exports is similar to object destructuring assignment.
We can only import what we can access by name.
So, the import statement below would fail (with our current module):
Import multiple named modules
We can import as many named exports as we like!
Let’s implement and export a chant
function:
My take
Named exports are the module feature I use most.
The major downside of named exports is naming collisions with other modules.
In future posts I’ll share a handful of strategies to compensate for and avoid naming collisions of named exports.
Go pro
This is part of a course I’m build on modules at lunch.dev.
When live, members get access to this and other courses on React.