Importing Everything with '*'
You'll learn how to import all named exports from a module at once using a single namespace object.
The Core Idea
Instead of importing each named export individually, JavaScript lets you grab everything a module exports using the asterisk (*) syntax. This bundles all named exports into a single object, giving you a tidy namespace to work with.
Think of it like ordering a combo meal instead of individual items—you get everything the restaurant offers in one convenient package.
The Syntax
When you import with *, you must use the as keyword to give the namespace a name:
import * as utils from './utilities.js';
This imports all named exports from utilities.js and packages them into an object called utils. You then access individual exports as properties:
// If utilities.js exported: add, subtract, multiply
utils.add(5, 3);
utils.subtract(10, 4);
utils.multiply(2, 6);
When to Use This Pattern
This approach shines when:
- A module exports many related functions or values
- You want clear namespacing (e.g.,
math.add()is more descriptive than justadd()) - You're unsure which exports you'll need and want them all available
The Trade-off
The asterisk imports everything, which can be less efficient than cherry-picking only what you need. However, modern bundlers often optimize this through tree-shaking.
Key Takeaway: Use import * as name to collect all named exports from a module into a single namespace object, accessing each export as a property of that object.