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
.tsor.jsin 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-netor--allow-readflags).
typescript
/* Wrong: missing file extension */ import { greet } from "./greet"; /* Right: with file extension */ import { greet } from "./greet.ts";
Quick Reference
| Import Type | Example | Notes |
|---|---|---|
| Local module | import { foo } from "./foo.ts"; | Must include file extension |
| Remote module | import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; | Use full URL with protocol |
| Default import | import React from "https://esm.sh/react"; | Imports default export |
| Named import | import { 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 ../