You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron项目集成@loaders.gl出现fetch未定义错误求助

问题:Electron集成@loaders.gl时出现fetch未定义错误

尝试在Electron.js项目中集成@loaders.gl,但构建时触发以下错误:

ReferenceError: fetch is not defined
    @loaders.gl/core/dist/es5/lib/fetch/fetch-file.js:42:13)

业务代码:

const { I3SConverter } = require("@loaders.gl/tile-converter");

module.exports = {
  convertFiles: async (url, outputPath) => {
    const converter = new I3SConverter();
    const tilesetJson = await converter.convert({
      inputUrl: url,
      outputPath: "data",
      inputType: "3DTILES",
      slpk: true,
      egmFilePath: "http://127.0.0.1:8081/deps/egm2008-5.pgm",
      tilesetName: "BatchedColors",
      token:
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWMxMzcyYy0zZjJkLTQwODctODNlNi01MDRkZmMzMjIxOWIiLCJpZCI6OTYyMCwic2NvcGVzIjpbImFzbCIsImFzciIsImdjIl0sImlhdCI6MTU2Mjg2NjI3M30.1FNiClUyk00YH_nWfSGpiQAjR5V2OvREDq1PJ5QMjWQ",
    });
  },
};

调用方式:

let inputFile = "http://127.0.0.1:8081/tileset.json";
convertFiles(inputFile, "");

已安装node-fetch但问题未解决,求可行的解决思路。


解决思路
  • 全局挂载fetch实现:安装node-fetch后,需在Electron对应进程中全局注入。主进程入口文件添加:

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

    渲染进程则改为挂载到window对象:

    const fetch = require('node-fetch');
    window.fetch = fetch;
    
  • 给I3SConverter传入自定义fetch:@loaders.gl支持手动指定fetch实现,初始化转换器时传入配置:

    const fetch = require('node-fetch');
    const { I3SConverter } = require("@loaders.gl/tile-converter");
    
    module.exports = {
      convertFiles: async (url, outputPath) => {
        const converter = new I3SConverter({ fetch: fetch });
        // 后续convert调用逻辑不变
      }
    };
    
  • 检查Electron进程权限配置:若在渲染进程中调用,确保BrowserWindow的webPreferences配置正确:

    • 若开启nodeIntegration: true,可直接引入node-fetch;
    • 若禁用nodeIntegration,需通过预加载脚本注入fetch:
      // preload.js
      const { contextBridge } = require('electron');
      const fetch = require('node-fetch');
      contextBridge.exposeInMainWorld('fetch', fetch);
      
      然后在BrowserWindow配置中关联preload文件:
      new BrowserWindow({
        webPreferences: {
          preload: path.join(__dirname, 'preload.js'),
          contextIsolation: true
        }
      });
      
  • 升级Electron使用内置fetch:Electron 18及以上版本已在主/渲染进程内置fetch API,无需依赖node-fetch,升级后可直接使用原生fetch,避免依赖冲突。

  • 验证@loaders.gl版本兼容性:检查当前@loaders.gl版本是否与所用Electron/Node.js版本适配,尝试升级到最新稳定版,部分旧版本可能存在环境适配问题。


内容的提问来源于stack exchange,提问作者sunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:09:24