Exporting from Modules

To make variables, functions, or classes available outside a module, you need to export them. You can export individual items inline or export everything at once at the end of the file.

Inline Exports with export

You can export items as you declare them by placing the export keyword before the declaration:

// account.js
let balance = 0;
export const INTEREST_RATE = 0.2;

export function deposit(amount) {
  balance += amount;
}

export function withdraw(amount) {
  balance -= amount;
}

export function getBalance() {
  return balance;
}

In this example, we export the INTEREST_RATE constant and three functions: deposit, withdraw, and getBalance. Other modules can now import these items. The balance variable stays private to the module.

Exporting at the End of a File

You can also declare everything first and export at the end with an export statement:

// account.js
let balance = 0;
const INTEREST_RATE = 0.2;

function deposit(amount) {
  balance += amount;
}

function withdraw(amount) {
  balance -= amount;
}

function getBalance() {
  return balance;
}

export { INTEREST_RATE, deposit, withdraw, getBalance };

This way, all the exports are in one place, so you can see them at a glance.

Export Aliases with as

You can give an alias to an exported value using the as keyword:

export { INTEREST_RATE as interest, deposit, withdraw, getBalance };

Other modules will now import interest instead of INTEREST_RATE.

Multiple Export Statements

You can also split exports into multiple statements (though this is less common):

export { INTEREST_RATE as interest };
export { deposit, withdraw, getBalance };