如何为节点模块提供 polyfill

How to provide a polyfill to a node module

我正在尝试在 NodeJS/express 服务器中使用 unsplash-js 模块。正如文档所说:"This library depends on fetch to make requests to the Unsplash API. For environments that don't support fetch, you'll need to provide a polyfill"。 我试过类似的东西,我很羞于展示,但为了学习我会

const Unsplash = require('unsplash-js').default;
const fetch = require('node-fetch');

Unsplash.prototype.fetch = fetch;

const unsplash = new Unsplash({
  applicationId: process.env.UNSPLASH_API_KEY,
});

还有这个

Node.prototype.fetch = fetch;

当然,没有任何效果。 我该怎么做?

您需要将 fetch 设置为全局变量,如下所示:

global.fetch = require('node-fetch')