0

我正在开发一个 PDF 查看器,基本上,它是一个mozilla pdf.js 项目。我克隆了 repo 并安装了依赖项,一切正常,即使我尝试通过 构建项目gulp generic,它也可以正常工作。

问题开始时我已经安装electron,创建查看器的桌面版本,即使在电子应用程序中一切仍然有效,但我习惯于const { ipcRenderer } = require('electron')从浏览器窗口向主进程发送消息。在我尝试使用 构建应用程序之前,它也可以正常工作gulp generic,它会显示一个错误Module not found: Error: Can't resolve 'fs' in '/*******/pdf.js/node_modules/electron'。当我require('electron')从脚本中删除它时,它会正确构建。

我的代码

function webViewerLoad() {
  const isElectron =
    navigator.userAgent.toLowerCase().indexOf(" electron/") > -1;
  if (isElectron) {
    const { ipcRenderer } = require("electron");
    ipcRenderer.send("electron:reload", v);
  }
}


  document.addEventListener("DOMContentLoaded", webViewerLoad, true);

错误

在此处输入图像描述

4

1 回答 1

0

如果有人陷入同样的​​境地,经过安静的研究,我已经通过几步解决了。

首先,我一直在使用electron.js我的客户端代码,并且我一直在使用const { ipcRenderer } = require("electron");. 如果您在浏览器控制台中输入,浏览器不知道 require,require您将收到错误消息。

要克服这个问题,您必须使用browserify或任何类似的工具。我一直在使用gulp.js, 在我的项目中。

其次,我使用的文件require('electron')有多个导入使用import file from 'somefile.js',所以这就是为什么browserify不捆绑它。我只需要在一个单独的.js文件中要求电子并捆绑它。

ipc_electron.js

const ipcRenderer  = window.require('electron'). ipcRenderer;
//Clear the localstorage when application is quitted/closed
window.addEventListener("message", ({ data }) => {
  if (data.type === "electron:reload") {
    ipcRenderer.send("electron:reload");
  }
});

ipcRenderer.on("pdf:url", _ => localStorage.clear());

Gulp.js

gulp.task("browserify", () => {
  console.log();
  console.log("### Browserifying ipc_electron.js");
  return browserify("./web/ipc_electron.js", {
    debug: true,
    extensions: [".js"],
    ignoreMissing: true,
    detectGlobals: false,
    bare: true,
    debug: false,
    builtins: false,
    commondir: false,
  })
    .exclude("fs")
    .exclude("electron")
    .exclude("electron-updater")
    .exclude("electron-settings")
    .exclude("path")
    .exclude("url")
    .exclude("sqlite3")
    .exclude("express")
    .exclude("net")
    .exclude("body-parser")
    .bundle()
    .pipe(source("ipc_electron_bundle.js"))
    .pipe(gulp.dest("./web"));
});

于 2020-12-04T06:59:38.477 回答