To import all exports from a file, write import * as obj from './filename.js'
Here, filename.js
is the name of the file from which you want to import all the exported values.
Let's understand the process with the help of an example.
Suppose you have a file utils.js
that has exported multiple values such as function, class, and variable.
export function sum(a, b) { return a + b; } export class Rectangle { constructor(length, width) { this.length = length; this.width = width; } area() { return this.length * this.width; } } export const PI = 3.14;
Here is how you import all exports from the file.
import * as obj from './utils.js'; console.log(obj.PI); //3.14 console.log(obj.sum(3, 4)); //7 let rect = new obj.Rectangle(4, 5); console.log(rect.area()); //20
Both utils.js
and app.js
are in the same folder that is why we have used relative path.
This pattern of importing is used when the file exports a large number of values. The syntax imports everything and makes them available as members of an object. Then, you use the dot notation to access the exported values.
You can also explicitly specify all the exported values using the named import.
import {sum, Rectangle, PI} from './utils.js'; console.log(PI); //3.14 console.log(sum(3, 4)); //7 let rect = new Rectangle(4, 5); console.log(rect.area()); //20
Sometimes, the module that you are importing might have used default export. In that case, you can import by removing the curly braces or using the * as obj
syntax.
export default function sum(a, b) { return a + b; }
import * as obj from './utils.js'; console.log(obj.sum(3, 4)); //7
You might find a situation where a module has default and named exports.
export default function sum(a, b) { return a + b; } export class Rectangle { constructor(length, width) { this.length = length; this.width = width; } area() { return this.length * this.width; } } export const PI = 3.14;
Here is how you import the members.
import sum, {Rectangle, PI} from './utils.js'; console.log(sum(3, 4)); //7 let rect = new Rectangle(4, 5); console.log(rect.area()); //20 console.log(PI); //3.14