Namespace Imports
You'll learn how to import all named exports from a module as a single, organized object using the asterisk wildcard.
What Are Namespace Imports?
When a module exports many named values, importing each one individually can become verbose. Namespace imports let you import everything at once, grouped under a single object name. This is done using the * (asterisk) wildcard combined with the as keyword.
Think of it like ordering an entire menu section at a restaurant rather than naming each dish individually—you get everything bundled together in one convenient package.
The Syntax
import * as myNamespace from './module.js';
The * means "all named exports," and as myNamespace creates an object containing all those exports as properties.
How It Works
If a module exports multiple named values:
// math.js
export const pi = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
You can import them all as a namespace:
import * as math from './math.js';
console.log(math.pi); // 3.14159
console.log(math.add(2, 3)); // 5
console.log(math.multiply(4, 5)); // 20
Every named export becomes a property on the math object. This keeps your imports organized and prevents naming collisions.
When to Use It
Namespace imports work well when:
- A module has many related exports
- You want clear context for where functions come from
- You want to avoid cluttering your local scope
Key Takeaway: Use import * as namespace from 'module' to bundle all named exports into a single object, creating a clean, organized way to access module functionality.