Home > Software engineering >  FS - Use FS for Electron on Webpack 5
FS - Use FS for Electron on Webpack 5

Time:12-13

I recently upgraded my Quasar framework to v2 which uses Vue3, Electron 16 and Webpack 5.

When I tried to run my application, I keep getting this error:

Module not found: Can't resolve imported dependency "fs"

I understand that webpack 5 does not automatically do polyfills so I added these in my quasar.conf.js:

      chainWebpack (chain) {
        const nodePolyfillWebpackPlugin = require('node-polyfill-webpack-plugin')
        chain.plugin('node-polyfill').use(nodePolyfillWebpackPlugin)
      }

But this doesn't support polyfills for the fs module.

When I tried adding this:

        if (!cfg.resolve.fallback) {
          cfg.resolve.fallback = {}
          cfg.resolve.fallback.fs = false
        }

Now I get an error:

TypeError: fs.readFileSync is not a function

I also tried adding this in my package.json, same behavior (as expected):

  "browser": {
    "fs": false
  }

But then.. How can I use fs in my electron application?

CodePudding user response:

Was able to figure it out now. Adding it here in case anyone might need it in the future. I see a lot of people asking this question but got no resolution.

So.. I added this to electron-preload.js, since fs / built-in node modules are accessible via the renderer:

import { contextBridge } from 'electron'

const fs = require('fs')
contextBridge.exposeInMainWorld('electronFs', {
  readFileSync: fs.readFileSync,
  existsSync: fs.existsSync
  // Other fs methods here
})

And use it like this in Vue / JS / modules:

const fs = window.electronFs
const jsonContent = JSON.parse(fs.readFileSync(SOME_PATH))
  • Related