davidmyersdev / vite-plugin-node-polyfills

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

Bug: Cannot destructure property 'Uint8Array' of 'globalThis' as it is undefined. #104

Open GiovaniGuizzoYUB opened 2 weeks ago

GiovaniGuizzoYUB commented 2 weeks ago

Summary

I am trying to use this plugin for polyfilling Node into my vite applciation. It builds my website perfectly, but when used with vite dev, I get the following error:

TypeError: Cannot destructure property 'Uint8Array' of 'globalThis' as it is undefined.
    at node_modules/.pnpm/buffer@6.0.3_patch_hash=zkkuxompt5d553skpnegwi5wuy/node_modules/buffer/index.js (helpers.ts:226:31)
    at __require (helpers.ts:13:60)
    at shims/dist/index.js (helpers.ts:1919:46)
    at __init (helpers.ts:10:66)
    at shims/banner/index.cjs (helpers.ts:1927:13)
    at __require (helpers.ts:13:60)
    at helpers.ts:1933:5
    at helpers.ts:1934:3

this is my Vite config:

import { TanStackRouterVite } from "@tanstack/router-plugin/vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";
import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), TanStackRouterVite(), nodePolyfills()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
});

This line from helpers.ts seems to be the culprit:

var { Uint8Array: GlobalUint8Array, ArrayBuffer: GlobalArrayBuffer, SharedArrayBuffer: GlobalSharedArrayBuffer } = globalThis;

I am currently using v0.17.0 due to this bug: https://github.com/davidmyersdev/vite-plugin-node-polyfills/issues/81

Any suggestions?

GiovaniGuizzoYUB commented 2 weeks ago

For reference, if I try to use v0.22.0, I get the following error:

TypeError: Cannot read properties of undefined (reading 'Buffer')
    at helpers.ts:2:32

This is the culprit in helpers.ts:

globalThis.Buffer = globalThis.Buffer || __buffer_polyfill;

Build works fine. It only happens in vite dev.

If I set globals: { Buffer: false }, thne the same error occurs for global.

GiovaniGuizzoYUB commented 2 weeks ago

Progress. Changing from plugins: [react(), TanStackRouterVite(), nodePolyfills()], to plugins: [nodePolyfills(), react(), TanStackRouterVite()], seems to have fixed the issue on v0.22.0.