0
0
DenoHow-ToBeginner ยท 3 min read

How to Use the std Library in Deno: Simple Guide

In Deno, you use the standard library by importing modules directly from the https://deno.land/std URL. Simply import the needed module using ES module syntax, for example, import { serve } from "https://deno.land/std/http/server.ts";, and then use its functions in your code.
๐Ÿ“

Syntax

To use the std library in Deno, import modules using the full URL from https://deno.land/std. Use ES module import syntax with the exact path and file extension.

  • import: keyword to bring in modules
  • { moduleName }: the specific function or object you want
  • from "URL": the URL to the std module file
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";

serve(() => new Response("Hello from Deno std!"));
๐Ÿ’ป

Example

This example shows how to create a simple HTTP server using the std library's serve function. It listens on port 8000 and responds with a greeting message.

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

console.log("Server running on http://localhost:8000");

serve(() => new Response("Hello from Deno std!"), { port: 8000 });
Output
Server running on http://localhost:8000
โš ๏ธ

Common Pitfalls

Common mistakes when using the std library in Deno include:

  • Forgetting to include the full URL with version number, which can cause unexpected updates or errors.
  • Omitting the file extension .ts in the import path, which is required in Deno.
  • Not granting necessary permissions when running scripts that use std modules (e.g., network access for serve).
typescript
/* Wrong: Missing version and file extension */
// import { serve } from "https://deno.land/std/http/server.ts";

/* Right: Include version and .ts extension */
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";
๐Ÿ“Š

Quick Reference

Tips for using Deno std library:

  • Always specify the version in the URL to avoid breaking changes.
  • Use exact file paths with extensions.
  • Check the official std library docs for available modules.
  • Run scripts with proper permissions, e.g., deno run --allow-net for network access.
โœ…

Key Takeaways

Import std library modules using full URLs with version and file extension.
Use ES module syntax to bring in only what you need from std.
Always specify a version in the URL to keep your code stable.
Remember to run Deno scripts with the right permissions for std features.
Check the official std docs for updated modules and usage examples.