MDN self-hosted library · e01.org
import / notebook

import

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
import { myExport } from "/modules/my-module.js";
js
import { foo, bar } from "/modules/my-module.js";
js
import { reallyReallyLongModuleExportName as shortName } from "/modules/my-module.js";
js
// -- /modules/my-module.js --
const a = 1;
export { a as "a-b" };
js
import { "a-b" as a } from "/modules/my-module.js";
js
import myDefault from "/modules/my-module.js";
js
import myDefault, * as myModule from "/modules/my-module.js";
// myModule.default and myDefault point to the same binding
js
import myDefault, { foo, bar } from "/modules/my-module.js";
js
import { default as myDefault } from "/modules/my-module.js";
js
import * as myModule from "/modules/my-module.js";
js
myModule.doAllTheAmazingThings();
js
import "/modules/my-module.js";
js
myModule.doAllTheAmazingThings(); // myModule.doAllTheAmazingThings is imported by the next line

import * as myModule from "/modules/my-module.js";
js
// -- main.js --
const utils = require("./utils"); // Omit the "index.js" file name
const utils = require("./utils/index"); // Omit only the ".js" extension
const utils = require("./utils/index.js"); // The most explicit form
js
  // HTTP URLs
  import x from "https://example.com/x.js";
  // Data URLs
  import x from "data:text/javascript,export default 42;";
  // Data URLs for JSON modules
  import x from 'data:application/json,{"foo":42}' with { type: "json" };
js
// -- getPrimes.js --
/**
 * Returns a list of prime numbers that are smaller than `max`.
 */
export function getPrimes(max) {
  const isPrime = Array.from({ length: max }, () => true);
  isPrime[0] = isPrime[1] = false;
  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);
}
js
import { getPrimes } from "/modules/getPrimes.js";

console.log(getPrimes(10)); // [2, 3, 5, 7]
js
// -- my-module.js --
export let myValue = 1;
setTimeout(() => {
  myValue = 2;
}, 500);
js
// -- main.js --
import { myValue } from "/modules/my-module.js";
import * as myModule from "/modules/my-module.js";

console.log(myValue); // 1
console.log(myModule.myValue); // 1
setTimeout(() => {
  console.log(myValue); // 2; my-module has updated its value
  console.log(myModule.myValue); // 2
  myValue = 3; // TypeError: Assignment to constant variable.
  // The importing module can only read the value but can't re-assign it.
}, 1000);
js
import data from "./data.json" with { type: "json" };