Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Modules and Permissions

ES Modules and URL Imports

Understand how Deno resolves imports - ES modules, explicit file extensions, URL and remote imports, caching and lockfiles, dynamic import(), import.meta and circular dependencies.

A module is a file that exports some values and imports others. Deno uses only one module system: standard ES modules, the same import and export that browsers use. There is no require, no module.exports and no hidden lookup in a node_modules folder. What you write is exactly where Deno looks.

That makes Deno's rules short, and once you know them you can read any Deno project. This lesson covers local imports, remote imports by URL, the cache and lockfile, dynamic import() and import.meta.

Exporting and importing

A module exposes names with export:

TypeScript
// math.ts
export const PI = 3.14159;

export function circleArea(radius: number): number {
  return PI * radius ** 2;
}

export default function describe(): string {
  return "math helpers";
}

Another file imports them:

TypeScript
// main.ts
import describe, { circleArea, PI } from "./math.ts";
import * as math from "./math.ts"; // namespace import

console.log(describe(), circleArea(2), PI);
console.log(math.circleArea(1));

Rename on import with as, and re-export from another module to build a tidy public surface:

TypeScript
// mod.ts
export { circleArea as area } from "./math.ts";
export * from "./strings.ts";

A file named mod.ts is a Deno convention for "the entry point of this folder", like index.js in Node.js. Deno does not look for it automatically: you must import ./utils/mod.ts by name.

Rules for specifiers

The string after from is a specifier. Deno applies simple rules:

  1. Relative paths start with ./ or ../ and must include the extension: ./math.ts, not ./math.
  2. Absolute URLs are fetched: https://....
  3. Prefixed specifiers name a registry: jsr:, npm:, node:.
  4. Bare names such as "@std/assert" are allowed only if an import map in deno.json defines them (Import Maps and deno.json).

The extension rule surprises people coming from Node.js, but it removes guessing: the specifier is the file.

Modules run once

When two files import the same module, it is loaded and run once, and both receive the same instance. That is why a module is a good place for shared state:

Node.js Modules are singletons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The value count is a live binding: importing modules see the current value, not a copy. But importers cannot assign to it; only the exporting module can change it.

Importing from URLs

Because a specifier can be a URL, code can come from anywhere on the web:

TypeScript
import { sample } from "https://deno.land/[email protected]/collections/sample.ts";
import confetti from "https://esm.sh/canvas-confetti@1";

Deno downloads the file the first time, stores it in its cache and reuses it afterward. Practical advice:

  • Pin versions in the URL (@0.224.0). A URL without a version can change under you.
  • Prefer JSR and npm specifiers for libraries (next lesson), because they are versioned and verified.
  • Remote imports are limited to a short list of well-known hosts unless you pass --allow-import=host, because downloading code is itself a risk (see Permissions).

Deno does not keep a node_modules folder for URL imports. Everything sits in the shared cache, and deno info shows where. To fetch dependencies ahead of time, for example in a Docker build step, run:

Terminal
deno install --entrypoint main.ts

Lock files

To make sure the code you downloaded today is the same code you get tomorrow, Deno writes a deno.lock file next to deno.json. It records a hash of every remote module and package version. If a remote file changes, Deno refuses to run and reports a mismatch.

Terminal
deno run main.ts              # creates or updates deno.lock automatically
deno run --frozen main.ts     # fail if the lock file would change (good for CI)
deno cache --reload main.ts   # re-download, then update the lock

Commit deno.lock to version control. It is the equivalent of package-lock.json.

Dynamic import

A static import is hoisted and loaded before the code runs. When you need to load code conditionally or lazily, use the function form, which returns a promise:

TypeScript
const { default: render } = await import("./charts.ts");

const lang = Deno.env.get("LANG")?.startsWith("fr") ? "fr" : "en";
const messages = await import(`./i18n/${lang}.ts`);

You can also import JSON with an attribute, with no parsing step:

TypeScript
import config from "./config.json" with { type: "json" };
console.log(config.name);

Here is lazy loading in action. The data URL module is only fetched and run when the button is "pressed":

Node.js Lazy loading with import()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

import.meta

Each module has an import.meta object with information about itself:

TypeScript
console.log(import.meta.url);      // file:///home/me/app/main.ts
console.log(import.meta.filename); // /home/me/app/main.ts
console.log(import.meta.dirname);  // /home/me/app
console.log(import.meta.main);     // true for the entry file
console.log(import.meta.resolve("./data.txt")); // absolute URL string

import.meta.dirname and filename are only set for local files. For a remote module use import.meta.url. The main check lets a file run code only when started directly, as in Your First Deno Program.

Circular imports

If a.ts imports b.ts and b.ts imports a.ts, ES modules still load, but the first module to run sees the other's exports as not yet initialised. Using a const before its module has run throws a ReferenceError. Functions declared with function are hoisted, so circular references to functions often work. The robust cure is to restructure: move the shared piece into a third module.

flowchart LR
  A["a.ts"] --> B["b.ts"]
  B --> A
  A -.->|"move shared code"| C["shared.ts"]
  B -.-> C

A cycle between a and b is fixed by extracting shared.ts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which import is valid for a local file in Deno?

    Relative specifiers must include the file extension. require does not exist in Deno ES modules.
  2. 2. What does deno.lock protect you from?

    The lock file records hashes of dependencies; a mismatch stops the run.
  3. 3. How do you load a module only when it is needed?

    Dynamic import() returns a promise for the module and is evaluated at that moment.
  4. 4. What is import.meta.main?

    It is a boolean that is true only for the entry module.

Summary

  • Deno uses only ES modules: import and export.
  • Relative imports need the extension; there is no automatic index lookup.
  • URL, jsr:, npm: and node: specifiers say where code comes from; pin versions.
  • Modules run once and share live bindings.
  • deno.lock records dependency hashes; commit it and use --frozen in CI.
  • import() loads lazily; import.meta describes the current module.

Next: Import Maps and deno.json