0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Import from URL in Deno: Simple Guide

In Deno, you can import modules directly from a URL using the import statement with the full URL string. This allows you to use remote code without installing packages locally, for example: import { serve } from "https://deno.land/std/http/server.ts";.
๐Ÿ“

Syntax

Use the import statement followed by the module names in curly braces, then from and the full URL string in quotes. The URL must point to a valid JavaScript or TypeScript module.

  • import: keyword to bring in code
  • { module }: named exports you want to use
  • from: keyword to specify source
  • "URL": full web address of the module
typescript
import { serve } from "https://deno.land/std/http/server.ts";
๐Ÿ’ป

Example

This example imports the serve function from Deno's standard library URL and starts a simple HTTP server that responds with "Hello from Deno!".

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

const server = serve({ port: 8000 });
console.log("Server running on http://localhost:8000/");

for await (const req of server) {
  req.respond({ body: "Hello from Deno!" });
}
Output
Server running on http://localhost:8000/
โš ๏ธ

Common Pitfalls

1. Forgetting to use full URL: Deno requires the full URL including protocol (e.g., https://), not just a domain or path.
2. Using unsupported URLs: The URL must point to a valid module file, not a webpage.
3. Not having network permission: Deno runs with secure defaults, so you must allow network access with --allow-net when running scripts that import from URLs.
4. Caching issues: Deno caches remote modules locally; if you want to update, use deno cache --reload.

typescript
/* Wrong: Missing protocol */
// import { serve } from "deno.land/std/http/server.ts";

/* Right: Full URL with https */
import { serve } from "https://deno.land/std/http/server.ts";
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample
Import keywordBrings in code from a moduleimport { serve } from "URL";
Full URLMust include protocol and path"https://deno.land/std/http/server.ts"
Network permissionAllow network access to fetch modulesdeno run --allow-net script.ts
Cache reloadForce update cached modulesdeno cache --reload script.ts
โœ…

Key Takeaways

Always use the full URL with protocol when importing modules in Deno.
Run Deno scripts with --allow-net to enable network access for URL imports.
Deno caches remote modules locally; use --reload to refresh them.
Imported URLs must point to valid JavaScript or TypeScript modules.
Importing from URLs lets you use remote code without local installs.