📌  相关文章
📜  ReferenceError: fetch is not defined - TypeScript (1)

📅  最后修改于: 2023-12-03 15:34:42.287000             🧑  作者: Mango

Introduction to 'ReferenceError: fetch is not defined - TypeScript'

If you are a TypeScript developer and you encounter the error ReferenceError: fetch is not defined, it means that your code is trying to use the fetch function, which is not recognized by the TypeScript compiler by default.

fetch is a built-in function in most modern browsers that allows you to make HTTP requests to a server and receive the response. However, it is not part of the standard Node.js runtime environment, which is why TypeScript does not include it in its default libraries.

To fix this error, you need to add a polyfill for the fetch function, which is a piece of code that provides a similar functionality to the original function.

Possible Solutions
Using a Third-Party Library

One of the easiest ways to add a polyfill for fetch is to use a third-party library such as isomorphic-fetch or node-fetch. These libraries provide a compatible implementation of fetch that works both in browsers and in Node.js environment.

To use isomorphic-fetch or node-fetch, you need to install the library using a package manager such as npm, import it into your TypeScript code, and use the fetch function as usual.

import fetch from 'isomorphic-fetch';

fetch('https://api.example.com/my-endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
import fetch from 'node-fetch';

fetch('https://api.example.com/my-endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Adding a Fetch Polyfill Manually

If you prefer not to use a third-party library, you can also add a fetch polyfill manually. One popular fetch polyfill is whatwg-fetch, which is included in many frontend frameworks such as React.

To use whatwg-fetch in TypeScript, you need to install it using a package manager such as npm, import it into your code, and use the fetch function as usual.

import 'whatwg-fetch';

fetch('https://api.example.com/my-endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Conclusion

In summary, if you encounter the ReferenceError: fetch is not defined error in TypeScript, it means that your code is trying to use the fetch function, which is not recognized by the TypeScript compiler by default. To fix this error, you need to add a polyfill for the fetch function, either by using a third-party library or by adding a polyfill manually.