Importing
You need an import statement to import the values exported from a module.
// script.js file
import { deposit, widthraw, getBalance } from "./account.js";
console.log(getBalance());
deposit(100);
widthraw(20);
console.log(getBalance());
- The import statement must be placed at the top of your script/module file.
- The import statement begins with the
import
keyword. - Imported values are comma separated inside a pair of curly brackets.
- The
from
keyword is used to supply the location of the module relative to the current file.
As it can be seen in the image below, the value returned by getBalance
shows the balance
variable (in account.js
file) has been updated.
Notice, there is no requirement that we import everything a module exports. In the snippet above, I have not imported interest
(alias for the INTEREST_RATE
constant). In the snippet below, I only import the interest
:
// script.js file
import { interest } from "./account.js";
console.log(interest);
Here is the output to the browser console:
Note that it is not possible to import a value from a module that was not exported:
// script.js file
import { balance } from "./account.js";
console.log(balance);
Similar to exports, you can use aliases when importing:
// script.js file
import { deposit, widthraw, getBalance as balance } from "./account.js";
console.log(balance());
deposit(100);
widthraw(20);
console.log(balance());
Although not common, it is possible to break a long import statement into several import statements:
import { deposit, widthraw } from "./account.js";
import { getBalance as balance, interest } from "./account.js";
A common pattern is to import everything that's exported by a module into one object as shown in the example below:
// script.js file
import * as Account from "./account.js";
console.log(Account.getBalance());
Account.deposit(100);
Account.widthraw(20);
console.log(Account.getBalance());
Notice (1) there is no {}
in the import statement above. (2) The imported values are accessed with the dot notation (e.g.Account.getBalance()
).