Streams in Vite

I’m trying to use N3 to parse and query Turtle files in a Vite/Vue 3 project. The N3 readme says “N3.js seamlessly works in browsers via webpack or browserify” and I had trouble interpreting what that would mean in a Vite context. I made an attempt at properly learning all about bundling, but I did some trial and error in parallel, which in the end worked out fine:

First off, I had to add a shim for global in vite.config.js (thanks Richard Oliver Bray):

export default defineConfig({
   // ...
   define: {
     global: {},
   },
 });

Then I got problems when using N3.Store.match:

Uncaught TypeError: Cannot read properties of undefined (reading ‘call’)

The culprit was a line saying Stream.call(this), i.e. Stream is what’s undefined. Here’s where I got lost installing and aliasing various browserified forks, before I just did:

yarn add events

and voilĂ !

N3 uses the Node.js Stream class. In a browser environment, it instead uses EventEmitter from the events library. So we just had to get that in place.