grpc-web icon indicating copy to clipboard operation
grpc-web copied to clipboard

"require is not defined" error when using with Vite

Open wutipong opened this issue 1 year ago • 6 comments

I'm trying to add grpc-web client into a Sveltekit-based application. Here's the page load function (in Typescript, if that matters)

export const load: PageLoad = async ({ fetch, url }) => {
    const client = new MetaServiceClient("http://localhost:9000")
    const r = await client.list(new MetaListRequest(), null)

    console.log(r)
    return {
        ok: true
    }
};

And the output is

4:46:58 AM [vite] Error when evaluating SSR module /src/lib/grpc/service_pb.js:
|- ReferenceError: require is not defined
    at eval (/home/noom/mangaweb3-frontend/src/lib/grpc/service_pb.js:15:12)
    at instantiateModule (file:///home/noom/mangaweb3-frontend/node_modules/vite/dist/node/chunks/dep-df561101.js:55974:15)

where service_pb.js is the generated js file.

wutipong avatar Sep 12 '23 22:09 wutipong

+1

adlion avatar Oct 11 '23 20:10 adlion

+1

ap0xF avatar Nov 06 '23 08:11 ap0xF

+1

rayshoo avatar Mar 11 '24 17:03 rayshoo

@adlion @ap0xF @rayshoo Thanks for the interests!

I think this comment explained why require doesn't work directly, and provided an alternative way to make it work, and a demo app (https://github.com/a2not/vite-grpc-web).

Could you take a look at the solution and see if it works for you?

We will also look into improving this workflow to make it easier for Vite users as we go through the Typescript-ification of our codebase.

Thanks! 😃

sampajano avatar Mar 12 '24 01:03 sampajano

@sampajano Thank you for your comment. I had already confirmed this through many searches, but unfortunately, it didn't work for me as I created and used the proto stub file with javascript rather than typescript.(vite is also used as javscript) However, I did a simple build test in the repository you shared. It definitely works well. I need to study TypeScript, which I've been putting off. Thank you!!

rayshoo avatar Mar 12 '24 01:03 rayshoo

@rayshoo Ahh i see! Glad to hear that the demo app works at least! Typescript seems like the right bet indeed.. We are interested in improving our TS support going forward as well!

sampajano avatar Mar 12 '24 02:03 sampajano