How to use the NPM module in Deno?

Sandeep
2 min readJun 28, 2020

Deno 1.0.0 was released in May 2020. It Has built-in utilities like a dependency inspector (deno info), a code formatter (deno fmt), debugger, and Test runner. It also supports top-level await.

But Deno has been around only for 2 years now so a number of third party libraries are very less as compared to NPM repository. But don’t worry, If you are looking for a library that is not available at deno.land/x yet, Thanks to Deno, you can still run some npm packages in Deno.

Deno provides a Node compatibility layer, that will allow us to use some NPM packages that do not use non-polyfilled Node.js APIs.

Loading CommonJs Module

`createRequire(…)` is provided to create a `require `function for loading CJS modules. It also sets supported globals.

import { createRequire } from "https://deno.land/std/node/module.ts";
const require = createRequire(import.meta.url);
// Loads native module polyfill.
const path = require("path");
// Loads extensionless module.
const cjsModule = require("./my_mod");

As we know Deno runs in the Sandbox environment that means it does not have access to network, filesystem unless explicitly provided. To run and load the required module, Deno will need a file read permission.

deno run — allow-read yourcode.js

You can restrict it only to node_modules

deno run — allow-read=node_modules yourcode.js

Note:

  • You can not use NPM packages that use non-poly filled Node API.
  • Use only Deno’s third-party packages whenever possible.
  • Check all Deno compatible module here: Deno third-party modules
  • Some of the Deno APIs are still unstable, so might have to use

`— unstable` flag to enable it during runtime.

  • You can directly import some npm module that doesn’t use Nodejs built-in from ESM provider as mentioned below.

ESM CDN providers

Deno can import modules from any location on the web, like GitHub, a personal web server, or a CDN

Below CDN providers that allow you to use npm packages as ESM

For example, if you want to use “query-string” you can use unpkg

import queryString from https://unpkg.com/query-string@6.13.1/index.jsconst stringified = queryString.stringify(queryObj);

Using JSPM

import esprima from "https://dev.jspm.io/esprima";

const program = 'const answer = 42';
console.log(esprima.tokenize(program))

Summary

As Deno 1.0.0 was released very recently and Nodejs compatibility layer is still under development you might see better support for npm packages in the future. Use the Nodejs compatibility layer only when you have no option left otherwise always seek Deno third-party module available at deno.land/x.

--

--