Completion requirements
Examples
Standard Import
In this example, we create a re-usable module that exports a function to get all primes within a given range.
// getPrimes.js /** * Returns a list of prime numbers that are smaller than `max`. */ function getPrimes(max) { const isPrime = Array.from({ length: max }, () => true); isPrime[0] = isPrime[1] = false; isPrime[2] = true; for (let i = 2; i * i < max; i++) { if (isPrime[i]) { for (let j = i ** 2; j < max; j += i) { isPrime[j] = false; } } } return [...isPrime.entries()] .filter(([, isPrime]) => isPrime) .map(([number]) => number); }
import { getPrimes } from '/modules/getPrimes.js'; console.log(getPrimes(10)); // [2, 3, 5, 7]
Imported values can only be modified by the exporter
The identifier being imported is a live binding, because the module exporting it may mutate it and the imported value would change. However, the module importing it cannot re-assign it.
// my-module.js export let myValue = 1; setTimeout(() => { myValue = 2; }, 500);
// main.js import { myValue } from '/modules/my-module.js'; console.log(myValue); // 1 setTimeout(() => { console.log(myValue); // 2; my-module has updated its value myValue = 3; // TypeError: Assignment to constant variable. // The importing module can only read the value but can't re-assign it. }, 1000);