Import All Named Exports into One Variable

chantastic - Feb 2 '21 - - Dev Community

We can import all of a JavaScript module's contents into a single variable with * as.

import * as stringUtils from "./string-utils.mjs";
Enter fullscreen mode Exit fullscreen mode

Now stringUtils can reference any exports in string-utils.mjs using property access syntax.

import * as stringUtils from "./string-utils.mjs";stringUtils.chant("we will");stringUtils.hype("rock you");
Enter fullscreen mode Exit fullscreen mode

Where is this a good practice? #

Importing all named exports into a single variable is great feature for application code.

Consider these UI modules that have a similar export signatur.

email.js

export Item …;export List …;export ListItem …;export Controller …;
Enter fullscreen mode Exit fullscreen mode

contact.js

export Item …;export List …;export ListItem …;export Controller …;
Enter fullscreen mode Exit fullscreen mode

Renaming all of these named exports is super irritating!

import { List as EmailList, ListItem as EmailListItem, Controller as EmailController,} from "./email.js";import { List as ContactList, ListItem as ContactListItem, Controller as ContactController,} from "./contact.js";
Enter fullscreen mode Exit fullscreen mode

By reducing moduling imports to a single reference, we eliminate the need to rename the colliding exports.

import * as Email from "./email.js";import * as Contact from "./contact.js";// Email.List, Contact.List, Email.Item, Contact.Item, etc.
Enter fullscreen mode Exit fullscreen mode

And these namespaces guarantee that we never experience a collision between named exports.

My take #

This is my preferred way to import named exports. It has eliminated pointless hours spent justifying local references between modules I don't control.

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.

Join lunch.dev for videos

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .