0
0
JavascriptHow-ToBeginner · 3 min read

How to Import All from Module in JavaScript: Syntax and Examples

To import all exported members from a JavaScript module, use import * as alias from 'module-name'. This syntax gathers all exports into a single object named alias, letting you access each export as a property of that object.
📐

Syntax

The syntax to import all exports from a module is:

  • import: keyword to bring code from another file.
  • * as alias: means import everything and group it under the name alias.
  • from 'module-name': specifies the module file or package to import from.
javascript
import * as utils from './utils.js';
💻

Example

This example shows how to import all functions from a module named mathUtils.js and use them via the alias math.

javascript
// mathUtils.js
export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

// main.js
import * as math from './mathUtils.js';

console.log(math.add(2, 3));
console.log(math.multiply(4, 5));
Output
5 20
⚠️

Common Pitfalls

Common mistakes when importing all from a module include:

  • Forgetting to use as alias after *. You must name the object to access exports.
  • Trying to import default exports with *. Default exports are not included in * imports.
  • Using incorrect module paths or missing file extensions in some environments.
javascript
// Wrong: missing alias
import * from './utils.js'; // SyntaxError

// Correct:
import * as utils from './utils.js';
📊

Quick Reference

SyntaxDescription
import * as alias from 'module-name';Import all exports grouped under alias
alias.exportNameAccess a specific export from the module
import defaultExport from 'module-name';Import default export only
import { namedExport } from 'module-name';Import specific named export

Key Takeaways

Use import * as alias from 'module' to import all exports as one object.
Access each export as a property of the alias object, like alias.exportName.
You must provide an alias name after the asterisk; it cannot be omitted.
Default exports are not included in * imports and require separate import syntax.
Always check your module path and file extension to avoid import errors.