Javascript - Importing Default Values


Importing default values from a module is as simple as,

import multiply from "./moduleFile.js"; 

This import statement imports the default value from the module.

We do not use any curly braces unlike when we import named exports.

The name multiply in this case is local and will be used to refer to the default value imported from the module.

In case of modules that export both default and non-default values, you can import all the bindings using a single statement.

export let message = "42 is the answer to the everything."; 

export default function(a, b) { 
    return a * b; 

import multiply, { message } from "./moduleFile.js"; 

console.log(multiply (21, 2));    // 42 
console.log(message);             // "42 is the answer to the everything." 

You need to use a comma to separate the default local name and the non-default identifiers listed inside curly braces.

Make sure to always have the default before the non-default values.

Another way to import a default module with a specific local name would be:

import { default as multiply, message } from "./moduleFile.js"; 

In this case, multiply stores the default module exported from moduleFile.js.

Related Topic