by Sai gowtham

How to use the npm modules in Deno

Learn, how to use the npm modules or packages in a deno app.

Deno has a node compatibility module, which helps us to use npm packages that do not use non-polyfilled node.js APIs.

Using npm modules

To use npm modules in Deno, we need to import a createRequire from the https://deno.land/std/node/module.ts URL that gives us a require() function for loading the CommonJS modules.

Example:

app.js
import { createRequire } from "https://deno.land/std/node/module.ts";

const require = createRequire(import.meta.url);
const { format } = require("date-fns");

console.log(format(new Date(), "dd/MM/yyyy"));

In the above code, we are using the date-fns npm module from the node_modules folder.

To run the above code successfully, you need to allow deno to read your node_modules folder.

deno run --unstable --allow-read=node_modules  app.js

Output:

13/06/2020

Note: Some of the deno APIs are still unstable, so that we used --unstable flag to enable it during runtime.

Using npm modules from CDN

Similarly, we can also import npm modules from the cdn’s like pika.dev or jspm.io, etc.

Here is an example that imports the date-fns module from the jspm.io cdn.

app.js
import dateFns from "https://dev.jspm.io/date-fns";

console.log(dateFns.format(new Date(), "dd/MM/yyyy"));

or you can import any other packages from the npm using https://dev.jspm.io/package-name URL.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course