0
0
DenoHow-ToBeginner ยท 3 min read

How to Use npm: Specifier in Deno for Importing Packages

In Deno, you can import npm packages directly using the npm: specifier in your import statements, like import _ from "npm:lodash";. This tells Deno to fetch the package from the npm registry and use it in your project without extra setup.
๐Ÿ“

Syntax

The npm: specifier is used in import statements to load packages from the npm registry. It has this pattern:

  • import <name> from "npm:<package-name>"; - imports the default export.
  • import { <named> } from "npm:<package-name>"; - imports named exports.
  • You can also specify versions like npm:package@version.

This syntax tells Deno to resolve the package from npm automatically.

typescript
import _ from "npm:lodash";
import { join } from "npm:path";
import express from "npm:express@4.18.2";
๐Ÿ’ป

Example

This example shows how to import and use the lodash package using the npm: specifier in Deno.

typescript
import _ from "npm:lodash";

const array = [1, 2, 3, 4];
const reversed = _.reverse(array.slice());
console.log("Original array:", array);
console.log("Reversed array:", reversed);
Output
Original array: [ 1, 2, 3, 4 ] Reversed array: [ 4, 3, 2, 1 ]
โš ๏ธ

Common Pitfalls

Some common mistakes when using the npm: specifier in Deno include:

  • Forgetting to use the npm: prefix and trying to import npm packages like local files.
  • Not specifying a version, which may lead to unexpected updates.
  • Using packages that rely on Node.js built-in modules without polyfills, causing runtime errors.
  • Not running Deno with --unstable flag if required by your Deno version.
typescript
/* Wrong way: missing npm: prefix */
// import _ from "lodash"; // This will fail

/* Right way: include npm: prefix */
import _ from "npm:lodash";
๐Ÿ“Š

Quick Reference

UsageDescription
import pkg from "npm:package";Import default export from npm package
import { named } from "npm:package";Import named exports from npm package
import pkg from "npm:package@1.2.3";Import specific version of npm package
Use with Deno 1.28+ for best supportEnsure Deno version supports npm specifier
Run with --unstable if neededEnable unstable features if required
โœ…

Key Takeaways

Use the npm: prefix in import statements to load npm packages in Deno.
Specify package versions to avoid unexpected updates.
Check compatibility of npm packages with Deno's runtime environment.
Run Deno with --unstable flag if your version requires it for npm support.
Always test imported npm packages to ensure they work as expected in Deno.