Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deno: Provide Polyfills for Node.js Built-Ins

Does Deno have a way to shim/polyfill Node.js modules?

That is, let's say I have a typescript file that's part of a Node.js project, and it looks something like this

import { performance } from 'perf_hooks';

function hello() {
  console.log(performance.performance.timeOrigin)
  console.log("Hello World")
}

export {
  hello
}

I want to use this module in a deno program, so I do something like this

import {hello} from './some-module.ts'

function main() {
  hello()
}

However, I can't do this because there's no perf_hooks module in Deno.

% deno run main.ts 
Check file:///private/tmp/main.ts
error: TS2305 [ERROR]: Module '"deno:///none.d.ts"' has no exported member 'performance'.
import { performance } from 'perf_hooks';
         ~~~~~~~~~~~
    at file:///private/tmp/some-module.ts:1:10

I would like to write my own version of perf_hooks that implements the properties and methods I need, and then tell Deno Hey -- whenever anyone wants perf_hook use my module instead.

Does Deno have anything built in that would let me do this? If not is there some common practive/bundling technique that the Deno community uses to do this sort of thing.

like image 676
Alan Storm Avatar asked Mar 03 '26 19:03

Alan Storm


1 Answers

You can use https://deno.land/x/std/node. It provide some Node's built-in modules. For external modules, you can take a look at https://esm.sh (The syntax is https://esm.sh/<npm-pkg>.

And if you want to use it like NodeJS environment, you can do the following:

import { ... } from "module"; // Let's use NodeJS "module" module for this

Then specify an import map

{
  "imports": {
    "module": "https://deno.land/std/node/module.ts"
  }
}

Run with the --import-map flag

$ deno run --import-map=/path/to/import_map.json your_file.ts
like image 104
x7y62 Avatar answered Mar 05 '26 09:03

x7y62