3 ways to import node modules in deno
Siddharth
Posted on October 24, 2021
Migrating to Deno can be hard when you depend on Node modules. Until those Node modules get ported to Deno, you can use these three methods to import Node modules in Deno.
Method 1: Using the compatibility layer
There is a Node compatibility layer in Deno standard library, which allows you to require()
anything which is in node_modules
.
import { createRequire } from 'https://deno.land/std/node/module.ts';
const require = createRequire(import.meta.url);
const path = require('path');
const cjsModule = require('./my_mod');
const leftPad = require('left-pad');
It was buggy for me as I wasn't able to import every module, and the need to have node_modules
is also a downside, which brings me to...
Method 2: Import the source code
If you are lucky, the authors of the library may have the source code using ES6 imports (and doesn't import any node builtins) and you can import the source code directly from the URL (remember, you can import any URLs!)
For example, you could import lodash like so:
import cloneDeep from 'https://raw.githubusercontent.com/lodash/lodash/master/cloneDeep.js';
I got that URL by going to the file on GitHub and then clicking the raw button.
But sometimes, you also need to support all those node builtins. That brings me to...
Method 3: jspm.io
JSPM is a module CDN which allows you to import
any node module in the browser, and by extension that means that you can use it to import to deno too!
JSPM is the most reliable method so far, it is used in my Web Framework Sleek too!
So if you want to import the wonderful recast library, you can do this:
import recast from 'https://jspm.dev/recast';
And that's it, you can now use recast!
If you found this post helpful, spread the word! or follow me on twitter or over here to stay updated on my blog posts!
Posted on October 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.