nodejs
目前,wasm-pack
生成的 npm 模組需要您在 node 專案中使用 fetch polyfill。
如果使用了 wasm-pack build --target nodejs
建立的模組,您可能會遇到一些關於全域 Headers
、Request
、Response
和 fetch
Web API 的錯誤。
常見錯誤
ReqwestError(reqwest::Error { kind: Builder, source: "JsValue(ReferenceError: Headers is not defined
ReqwestError(reqwest::Error { kind: Builder, source: "JsValue(ReferenceError: Request is not defined
var ret = getObject(arg0) instanceof Response;
ReferenceError: Response is not defined
解決方法
匯入或宣告 fetch 以及物件:Headers、Request、Response
// CommonJS
const fetch = require('node-fetch');
// ES Module
import fetch from 'node-fetch';
// @ts-ignore
global.fetch = fetch;
// @ts-ignore
global.Headers = fetch.Headers;
// @ts-ignore
global.Request = fetch.Request;
// @ts-ignore
global.Response = fetch.Response;