Search code examples
node.jselectronpdf.js

Can't resolve 'fs' in Electron


I would like to use pdf.js in an Electron app. This lib uses several node module such as fs or zlib. When launching the app, I have many errors, one for each failing native node module import:

Module not found: Error: Can't resolve 'zlib' in '/Users/antoine/Desktop/black-charts-desktop/node_modules/pdf.js-extract/lib/pdfjs'

Yet, I have authorized node in my main window:

webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      nodeIntegration: true,
    },

How to use native node module in my Electron app?


Solution

  • The answer to this question depends on the version of Electron used and the type of solution to use webpack. The use of webpack is possible with this solution:

    https://webpack.electron.build/

    BTW: in general, it is not recommended to use nodeIntegration, however, I personally disagree. VSCode, Teams, Postman based on Electron successfully use nodeIntegration....

    In the "electron" version: "^20.0.3", to build applications without IPC, in the renderer process, you need to add the @electron/remote package.

    In addition, in package.json:

      "build": {
        "extraResources": [
          "./node_modules/@electron/remote/**"
        ]
      },
    

    If we want to use Typescript and Sass:

     "devDependencies": {
        "electron": "^20.0.3",
        "electron-builder": "^23.5.1",
        "electron-webpack": "^2.8.2",
        "electron-webpack-ts": "^4.0.1",
        "sass": "^1.49.9",
        "sass-loader": "^7.3.0",
        "typescript": "^3.8.3",
        "webpack": "4.42.1"
      },
    

    and the scripts can look like this, for example:

    "scripts": {
        "dev": "electron-webpack dev --host 0.0.0.0",
        "pack": "electron-builder --dir",
        "compile": "electron-webpack",
        "dist": "npm run compile && electron-builder".
    }