Reputation: 1021
How do you use GRPC-Web on the browser? I mean, in pure browser code, without any NodeJS involved.
Official example from here: https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld are mainly NodeJS oriented.
Is there way to use GRPC-Web in pure Javascript form without:
const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');
Meaning, just standard <script>
-way of adding Javascript dependencies?
And be able to do: var client = new GreeterClient('http://localhost:8080');
Upvotes: 4
Views: 1834
Reputation: 28948
grpc-web
, not @grpc/grpc-js
npm package.The example provided in Write Client Code uses @grpc/grpc-js
, which only works on NodeJS.
To use your protobufs and gRPC services defined in your .proto
files, you need to generate your code using grpc-web. Then, import those generated files and use them.
Upvotes: 1
Reputation: 31
Yes. You need to bundle your sources with webpack. This step is also described in the documentation you mentioned. At the bottom of the readme:
Just config your webpack to expose variable:
client.js
...
export function instantiateGreeterClient(...) {
return new GreeterClient(...)
};
webpack.config.js
module.exports = {
...
entry: './path/to/client.js',
output: {
path: './bundle/js/',
filename: 'grpc.js',
library: {
name: 'grpc',
type: 'umd',
},
...
}
And after that import your bundle as usual. Now you be able to use all defined variables in your script tag code as
<script src="path/to/grpc.js"></script>
<script>
const client = grpc.instantiateGreeterClient(...)
...
</script>
More information can be found in webpack documentation
Upvotes: 1