davidmyersdev/vite-plugin-node-polyfills

Bug: Cannot destructure property 'existsSync' of 'require_empty(...)

vitorioMarcapo opened this issue · 4 comments

Summary

I am getting the following error when I added the plugin
sanitize-html.js?v=a55f9d5f:6974 Uncaught TypeError: Cannot destructure property 'existsSync' of 'require_empty(...)' as it is null.

It's coming from the postcss, but from my understanding postcss is a dependency of vite and I am not sure how to deal with this.

My config so far is:
Screenshot at Jun 06 12-10-32
:

The problem is with the fs and path modules. Here is visible they are used by postcss inside previous.map.js:
Screenshot at Jun 06 12-12-54

Hello any updates ?

I am having the same issue. Has anyone found a solution?

The issue arises because polyfills substitute Node.js's fs module with a mock fs that is compatible with the browser but lacks certain methods like existsSync. I faced a similar problem, but since I was working with Electron.js, I resolved it by creating a new fs instance using contextBridge.e

//preload.js
contextBridge.exposeInMainWorld('electron', {
//...
fs: {
    statSync: (filePath) => fs.statSync(filePath),
    isDirectory: (filePath) => {
      const stats = fs.statSync(filePath);
      return stats.isDirectory();
    },
    isFile: (filePath) => {
      const stats = fs.statSync(filePath);
      return stats.isFile();
    },
    lstatSync: (...args) => { return fs.lstatSync(...args) },
    writeFileSync: (...args) => { return fs.writeFileSync(...args) },
    readFileSync: (path, ...args) => { return fs.readFileSync(path, ...args) }
    //in your case add existSync

  },

If you’re not using Electron, which appears to be the case, you can try adding the following to your vite.config.js:

export default defineConfig({
  plugins: [
    nodePolyfills({
      overrides: {
        // Since `fs` is not supported in browsers, we can use mock fs packages to polyfill it.
        fs: 'browserify-fs',
      },
    }),
//...

The override was what I needed. Thank you.