Deno:为 Node.js 内置提供 Polyfill

Ala*_*orm 2 javascript polymorphism polyfills deno

Deno 是否有办法填充/填充 Node.js 模块?

也就是说,假设我有一个属于 Node.js 项目一部分的打字稿文件,它看起来像这样

import { performance } from 'perf_hooks';

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

export {
  hello
}
Run Code Online (Sandbox Code Playgroud)

我想在 deno 程序中使用这个模块,所以我做了这样的事情

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

function main() {
  hello()
}
Run Code Online (Sandbox Code Playgroud)

但是,我不能这样做,因为 Deno 中没有perf_hooks模块。

% 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
Run Code Online (Sandbox Code Playgroud)

我想编写我自己的版本perf_hooks来实现我需要的属性和方法,然后告诉 Deno Hey - 每当有人想要perf_hook使用我的模块时

Deno 有内置的东西可以让我做到这一点吗?如果没有,Deno 社区是否使用一些常见的实践/捆绑技术来完成此类事情。

小智 6

您可以使用https://deno.land/x/std/node。它提供了一些Node的内置模块。对于外部模块,您可以查看https://esm.sh(语法为https://esm.sh/<npm-pkg>.

如果你想像 NodeJS 环境一样使用它,你可以执行以下操作:

import { ... } from "module"; // Let's use NodeJS "module" module for this
Run Code Online (Sandbox Code Playgroud)

然后指定导入映射

import { ... } from "module"; // Let's use NodeJS "module" module for this
Run Code Online (Sandbox Code Playgroud)

--import-map带着旗帜奔跑

{
  "imports": {
    "module": "https://deno.land/std/node/module.ts"
  }
}
Run Code Online (Sandbox Code Playgroud)