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:
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.
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.