0
0
DenoHow-ToBeginner ยท 3 min read

How to Use npm Packages in Deno: Simple Guide

Deno supports using npm packages by enabling the --unstable flag and importing packages with the npm: prefix in your import statements. You can install and use npm packages directly without a separate package manager by running your script with deno run --unstable --allow-net.
๐Ÿ“

Syntax

To use an npm package in Deno, import it using the npm: prefix followed by the package name. Run your script with the --unstable flag to enable npm support and --allow-net to allow network access for fetching packages.

  • import pkg from "npm:package-name"; - imports the npm package.
  • deno run --unstable --allow-net your_script.ts - runs the script with necessary permissions.
typescript
import lodash from "npm:lodash";

console.log(lodash.camelCase('hello world from deno'));
๐Ÿ’ป

Example

This example shows how to import the popular lodash npm package in Deno and use its camelCase function to convert a string.

typescript
import lodash from "npm:lodash";

console.log(lodash.camelCase('hello world from deno'));
Output
helloWorldFromDeno
โš ๏ธ

Common Pitfalls

Common mistakes when using npm packages in Deno include:

  • Not using the --unstable flag, which is required for npm support.
  • Forgetting to add --allow-net permission to fetch packages from the internet.
  • Trying to import npm packages without the npm: prefix.
  • Using packages that rely on Node.js built-in modules without polyfills, which may cause errors.

Always check if the npm package works in Deno or if you need a Deno-specific alternative.

typescript
/* Wrong way: missing npm: prefix and flags */
// import lodash from "lodash";

/* Right way: */
import lodash from "npm:lodash";

console.log(lodash.camelCase('hello world'));
๐Ÿ“Š

Quick Reference

  • Import syntax: import pkg from "npm:package-name";
  • Run script: deno run --unstable --allow-net your_script.ts
  • Permissions: --allow-net needed to fetch packages
  • Prefix: Always use npm: before package name
  • Compatibility: Some Node.js packages may not work without polyfills
โœ…

Key Takeaways

Use the npm: prefix in import statements to load npm packages in Deno.
Run scripts with --unstable and --allow-net flags to enable npm support and network access.
Not all npm packages work in Deno; check compatibility or use Deno-specific modules.
Always include necessary permissions to avoid runtime errors when fetching packages.
Using npm packages in Deno simplifies dependency management without a separate package.json.