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
--unstableflag, which is required for npm support. - Forgetting to add
--allow-netpermission 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-netneeded 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.