electron - 找不到模块 : Error: Can't resolve 'fs' - Electron

标签 electron pdf.js pdfjs-dist

我正在开发 PDF 查看器,基本上,它是 mozilla pdf.js project .我克隆了 repo 并安装了依赖项,一切正常,即使我尝试通过 gulp generic 构建项目也是如此,它可以正常工作。
当我安装 electron 时问题开始了,要创建查看器的桌面版本,即使在 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);

错误
enter image description here

最佳答案

如果有人陷入同样的​​境地,经过安静的研究,我已经通过几步解决了。
首先我一直用electron.js在我的客户端代码和我一直使用的 const { ipcRenderer } = require("electron"); .如果您输入 require,浏览器不知道 require在浏览器控制台中,您将收到错误消息。
要超越这个问题,你必须使用 browserify或任何类似的工具。我一直在使用gulp.js ,在我的项目中。
其次,我用过的文件require('electron')在,使用了多个导入 import file from 'somefile.js' ,这就是为什么browserify没有捆绑它。我只需要在单独的 .js 中要求 Electron 文件并捆绑它。
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"));
});

关于electron - 找不到模块 : Error: Can't resolve 'fs' - Electron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65108773/

相关文章:

javascript - 建立一个 Electron 项目需要多长时间?

vue.js - 如何在 Electron 战中使窗口成为前景

javascript - 如何下载在 pdf.js 中打开的 Canvas 渲染的 pdf 文件?

typescript pdfjs-dist : You may need an additional loader

reactjs - 如何对 Electron 应用程序进行性能测试?

javascript - Pdf.js : How to load file + view -- An error occurred while loading the PDF. 更多信息关闭(搜索 "normal"示例)

javascript - 如何打印pdf.js文件?

javascript - Mozilla PDF - 如何从 react 应用程序中的 url 查看 PDF?

javascript - 参数值突然变化