davidmyersdev / vite-plugin-node-polyfills

A Vite plugin to polyfill Node's Core Modules for browser environments.
MIT License
310 stars 22 forks source link

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

Open vitorioMarcapo opened 5 months ago

vitorioMarcapo commented 5 months ago

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

Gitssalah commented 4 months ago

Hello any updates ?

luisamiranda commented 3 months ago

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

Gitssalah commented 3 months ago

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',
      },
    }),
//...
luisamiranda commented 3 months ago

The override was what I needed. Thank you.