0
0
DenoHow-ToBeginner ยท 3 min read

How to Import Modules in Deno: Syntax and Examples

In Deno, you import modules using the ES module syntax with import statements. You can import modules from URLs or local file paths by specifying the full path or URL in the from clause.
๐Ÿ“

Syntax

The basic syntax to import a module in Deno uses the ES module import statement. You specify what to import and from where.

  • import: keyword to bring code from another file or URL.
  • { ... }: named imports to pick specific parts.
  • from: keyword to specify the module source.
  • "./path/to/module.ts": local file path or URL of the module.
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";
import { myFunction } from "./my_module.ts";
๐Ÿ’ป

Example

This example shows how to import a function from a local file and a module from a URL, then use them.

typescript
import { greet } from "./greet.ts";
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";

console.log(greet("friend"));

serve(() => new Response("Hello from Deno server!"), { port: 8000 });
Output
friend, hello! # (and starts a server on port 8000)
โš ๏ธ

Common Pitfalls

Common mistakes when importing modules in Deno include:

  • Not using file extensions like .ts or .js in local imports, which Deno requires.
  • Forgetting to use full URLs with protocol (https://) when importing remote modules.
  • Using relative paths incorrectly (always start with ./ or ../ for local files).
  • Trying to import modules without proper permissions when running Deno (use --allow-net or --allow-read flags).
typescript
/* Wrong: missing file extension */
import { greet } from "./greet";

/* Right: with file extension */
import { greet } from "./greet.ts";
๐Ÿ“Š

Quick Reference

Import TypeExampleNotes
Local moduleimport { foo } from "./foo.ts";Must include file extension
Remote moduleimport { serve } from "https://deno.land/std@0.203.0/http/server.ts";Use full URL with protocol
Default importimport React from "https://esm.sh/react";Imports default export
Named importimport { readFileStr } from "https://deno.land/std/fs/mod.ts";Imports specific exports
โœ…

Key Takeaways

Always use full file extensions for local module imports in Deno.
Remote modules must be imported using full URLs including the protocol.
Use ES module syntax with import and from keywords.
Check Deno permissions when importing modules that access network or file system.
Relative paths for local files must start with ./ or ../