[英]Using GRPC-Web without NodeJS
How do you use GRPC-Web on the browser?如何在浏览器上使用 GRPC-Web? I mean, in pure browser code, without any NodeJS involved.我的意思是,在纯浏览器代码中,不涉及任何 NodeJS。
Official example from here: https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld are mainly NodeJS oriented.来自这里的官方示例: https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld主要面向 NodeJS。
Is there way to use GRPC-Web in pure Javascript form without:有没有办法以纯 Javascript 形式使用 GRPC-Web,而无需:
const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');
Meaning, just standard <script>
-way of adding Javascript dependencies?意思是,只是标准<script>
-添加 Javascript 依赖项的方式? And be able to do: var client = new GreeterClient('http://localhost:8080');
并且能够做到: var client = new GreeterClient('http://localhost:8080');
Yes.是的。 You need to bundle your sources with webpack.您需要将源代码与 webpack 捆绑在一起。 This step is also described in the documentation you mentioned.您提到的文档中也描述了此步骤。 At the bottom of the readme :在自述文件的底部:
Just config your webpack to expose variable:只需配置您的 webpack 即可公开变量:
client.js客户端.js
...
export function instantiateGreeterClient(...) {
return new GreeterClient(...)
};
webpack.config.js 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更多信息可以在webpack 文档中找到
grpc-web
, not @grpc/grpc-js
npm package.使用grpc-web
,而不是@grpc/grpc-js
npm package。 The example provided in Write Client Code uses @grpc/grpc-js
, which only works on NodeJS. 编写客户端代码中提供的示例使用@grpc/grpc-js
,它仅适用于 NodeJS。
To use your protobufs and gRPC services defined in your .proto
files, you need to generate your code using grpc-web .要使用.proto
文件中定义的 protobuf 和 gRPC 服务,您需要使用grpc-web生成代码。 Then, import those generated files and use them.然后,导入这些生成的文件并使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.