177177177
17717717712mo ago

How to monkey patch an installed third party deno module.

Is it possible to monkey patch an installed third party deno module?? I want to overwrite a function from a third party module that I'm using so the function logic gets updated everywhere.
2 Replies
Deno AI Helper
Deno AI Helper12mo ago
Monkey patching a third-party module in Deno can be a bit tricky due to the way Deno handles module resolution and caching. However, you can achieve something similar to monkey patching by using a couple of techniques. Here's a general approach based on the documentation: 1. Vendoring the Module: Deno provides a deno vendor command that allows you to download and store the dependencies of your project locally in a vendor directory. This command also generates an import map that maps the remote modules to your local vendor directory.
$ deno vendor main.ts
$ tree
.
├── main.ts
└── vendor
├── deno.land
├── import_map.json
└── raw.githubusercontent.com
$ deno run --no-remote --import-map=vendor/import_map.json main.ts

$ deno vendor main.ts
$ tree
.
├── main.ts
└── vendor
├── deno.land
├── import_map.json
└── raw.githubusercontent.com
$ deno run --no-remote --import-map=vendor/import_map.json main.ts

By vendoring the module, you can directly modify the code of the vendored module in your local vendor directory. This allows you to change the function logic as needed. 2. Using Import Maps: Import maps allow you to remap imports to different URLs or local file paths. You can create an import map that points to your patched version of the module.
{
"imports": {
"https://deno.land/x/example/": "./patched/"
}
}

{
"imports": {
"https://deno.land/x/example/": "./patched/"
}
}

In this example, any import from https://deno.land/x/example/ would be redirected to the local ./patched/ directory where you have your modified version of the module. Remember to use the --import-map flag when running your Deno program to ensure that Deno uses the import map you've defined. Please note that while these methods allow you to modify the behavior of a third-party module, they are not as straightforward as traditional monkey patching in dynamic languages like JavaScript running in Node.js. The
Deno AI Helper
Deno AI Helper12mo ago
vendored code should be checked into version control, and you should be cautious about maintaining your patches when the upstream module gets updated. 🦕