Provide a dynamic cjs wrapper built in to node-fetch that import(..)
See original GitHub issueBased on the documentation jimmywarting linked above, I created a helper typescript file that hopefully can serve other typescript users that are stuck:
// node-fetch.ts // Helps importing node-fetch based on https://github.com/node-fetch/node-fetch/issues/1279 import type fetch from 'node-fetch'; export { RequestInit } from 'node-fetch'; // TODO: add more exports as needed here // eslint-disable-next-line no-eval const fetchPromise: Promise<typeof fetch> = eval('import("node-fetch")').then((mod: { default: typeof fetch }) => mod.default); const exportedFetch: typeof fetch = (...args) => fetchPromise.then(fetch => fetch(...args)); export default exportedFetch;
Now, just import it with
import fetch, { RequestInit } from './node-fetch';
almost as usual (note the./
)It would be handy if such script was directly embedded in the package, like
import fetch, { RequestInit } from 'node-fetch/cjs.js';
.
_Originally posted by @jeremyVignelles in https://github.com/node-fetch/node-fetch/issues/1266#issuecomment-925813598_
I think this is a good solution that dose not involve introducing a bundler and compiling everything into one file and importing all dependencies and basically duplicating everything. or using complex tools such as esbuild
, noesm
.
This dynamic import()
have been suggested too many already and seems like good temporary easy solution.
I’m wondering if we should go ahead and introduce something like it built in to node-fetch. there is also the method such as lazy import only when needed: https://github.com/node-fetch/node-fetch/issues/1279#issuecomment-915063354 that i think is good solution also. it can have a faster boot up time. basically goes like this:
const _importDynamic = new Function('modulePath', 'return import(modulePath)')
module.exports = async function fetch(...args) {
const {default: fetch} = await _importDynamic('node-fetch'))
return fetch(...args))
}
One take a way from developers who uses a bundler/test framework such as jest, webpack, rollup, ts-node, ts-node-dev etc is that they like to rewrite the import()
statement to require()
or something like it. therefore i think a eval/new Function
solution would be a good option
One thing to note doe is that it won’t export Headers
, Request
and Response
in a sync manner but most ppl only use the fetch method anyways(?) - would need to be documented that this dose not do the same thing
Issue Analytics
- State:
- Created 2 years ago
- Comments:13 (1 by maintainers)
Top GitHub Comments
Some trouble. It’s a mess. I can’t use ES modules in a serverless environment. The typescript compiles a dynamic import to
require
.@types/node-fetch
is deprecated. What do you want me to do?This is fixed in the latest TypeScript beta, which should be out in ~1 month 🎉
https://devblogs.microsoft.com/typescript/announcing-typescript-4-5-beta/