【问题标题】:Module not found: Error: Can't resolve 'fs' - Electron未找到模块:错误:无法解析 'fs' - Electron
【发布时间】:2020-12-04 14:59:38
【问题描述】:

我正在开发 PDF 查看器,基本上,它是 mozilla pdf.js project。我克隆了 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);

错误

【问题讨论】:

标签: electron pdf.js pdfjs-dist


【解决方案1】:

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

首先,我一直在我的客户端代码上使用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"));
});

【讨论】:

    猜你喜欢
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2018-06-29
    • 2019-12-01
    • 2018-04-11
    • 2018-09-30
    相关资源
    最近更新 更多