How do you get an NPM package running in Deno? There are multiple answers to this question, some simple and others more complex. NPM holds a few million packages filled with all sorts of JavaScript and Typescript that help developers to work faster (Actually, 90% are for printing strings on the console in pretty colors). Meanwhile, Deno has its own registry deno.land/x which contains round and about 2500 modules at the moment.

That may sound a bit sparse, but the good news is that we can use quite a number of Node modules in Deno without too much effort by making use of some clever build tools that people around the globe have been working on. In addition, many of the smaller NPM packages can be converted with only a little effort. The real tough ones are larger Node projects which often depend on many other packages, which in turn can also have their own dependencies, creating a big dependency tree full of potential issues when run in Deno.

You may wonder why any changes are even required. It is all just JavaScript, right? True, but Deno and most of Node use different module systems. The Node standard for a number of years was CommonJS which is used by any code that has require(...) and module.exports = ... syntax. CommonJS was a non-native module specification that emerged from the wish of JS devs to organize their ever growing codebases into separated modules, just like in many other programming languages. Since 2015 JavaScript has released a native module solution: ECMAScript modules or ES Modules, that uses import and export syntax. One of the reasons for Node code not working in Deno can be that it is using the CommonJS module system.

Another reason for incompatibility is that Deno was redesigned from the ground up to improve upon some of the design flaws of Node.js. For this reason, core Node modules such as httpfs and crypto will not work or only partially in Deno, because under the hood the way that these modules work has simply diverged too much between the two runtimes.

For now, enough background though. Let’s see some approaches for getting Node code to Deno land.

Content Delivery Networks (CDNs)

The easiest conversion method is to have all the work be done for you. In recent years a few build tools have emerged that can take a CommonJS module and convert it to an ES Module automatically, and more! They enable importing code from a CDN with a URL just like in good old browser JavaScript. Say that you wanted to use ms, an NPM package that converts all sorts of time formats to and from milliseconds. We can use it in Deno as follows:

import ms from "https://cdn.skypack.dev/ms";

console.log(ms(1000));
> 1s

#typescript #deno #javascript #modules

The Deno Post — Converting Node Code
1.30 GEEK