badgateway / ketting

The HATEOAS client for javascript
https://www.npmjs.com/package/ketting
MIT License
548 stars 32 forks source link

`Cannot access "stream.Stream" in client code` when using ketting w/ ViteJS #470

Open jamesdh opened 1 year ago

jamesdh commented 1 year ago

I recently converted one of our web apps from Create React App to Vite. Now in the process of replacing some legacy code w/ ketting. Ketting worked fine in another CRA app of ours, but when attempting to use the latest (8.0.0-alpha.2) w/ Vite, I get the following on startup:

Module "stream" has been externalized for browser compatibility. Cannot access "stream.Stream" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.
get @ index.js:15
(anonymous) @ sax.js:20
node_modules/sax/lib/sax.js @ sax.js:1414
__require2 @ chunk-TFWDKVI3.js?v=4593b7b9:18
node_modules/ketting/dist/util/html.js @ sax.js:1424
__require2 @ chunk-TFWDKVI3.js?v=4593b7b9:18
node_modules/ketting/dist/state/html.js @ sax.js:1520
__require2 @ chunk-TFWDKVI3.js?v=4593b7b9:18
node_modules/ketting/dist/state/index.js @ html.ts:82
__require2 @ chunk-TFWDKVI3.js?v=4593b7b9:18
(anonymous) @ html.ts:93

Per Vite:

When you use a Node.js module in the browser, Vite will output the following warning.

Module "fs" has been externalized for browser compatibility. Cannot access "fs.readFile" in client code. This is because Vite does not automatically polyfill Node.js modules.

We recommend avoiding Node.js modules for browser code to reduce the bundle size, although you can add polyfills manually. If the module is imported from a third-party library (that's meant to be used in the browser), it's advised to report the issue to the respective library.

I was able to simply yarn add stream and get around this. I don't fully understand the issue or Vite's suggestion, but I thought I'd raise this nonetheless.

jamesdh commented 1 year ago

FWIW, vite-plugin-node-polyfills got ketting working w/ Vite.

evert commented 1 year ago

Thank you, this is helpful. Webpack will actually use a browser-specific build of Ketting that doesn't have the sax dependency, but it looks like Vite doesn't do this. We do a number of optimizations for browsers that make the build a lot leaner by relying on browser APIs when possible.

So i want to keep this open with the intention of figuring out how we can get Vite make better decisions.