Streams in Vite

by

in

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.


Comments

2 responses to “Streams in Vite”

  1. WORKS!

    Installing the `events` was the last missing thing for me.

    I was fighting for hours with switching from `vue-cli` to `vite`, on of the harder things was the `Stream.call(this);` crying that `Stream` is not defined.

    So I’m leaving this here, might help someone out too.

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import path from 'path'
    export default defineConfig({
        plugins: [vue()],
        define: {
            'process.env.NODE_DEBUG' : "'development'",
            'global'                 : {
                "Uint8Array": Uint8Array
            },
        },
        resolve: {
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
            alias: {
                '@' : path.resolve(__dirname, './src'),
                "stream" : require.resolve("stream-browserify"),
            },
        },
    })
    
  2. it works in dev but not work in build

Leave a Reply

Your email address will not be published. Required fields are marked *