【问题标题】:Using GRPC-Web without NodeJS在没有 NodeJS 的情况下使用 GRPC-Web
【发布时间】:2021-03-08 20:56:35
【问题描述】:

如何在浏览器上使用 GRPC-Web? 我的意思是,在纯浏览器代码中,不涉及任何 NodeJS。

来自此处的官方示例:https://github.com/grpc/grpc-web/tree/master/net/grpc/gateway/examples/helloworld 主要面向 NodeJS。

有没有办法以纯 Javascript 形式使用 GRPC-Web,而无需:

const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');

意思,只是标准的<script>-添加Javascript依赖的方式? 并且能够做到:var client = new GreeterClient('http://localhost:8080');

【问题讨论】:

    标签: javascript grpc grpc-web


    【解决方案1】:

    是的。您需要将源代码与 webpack 捆绑在一起。您提到的文档中也描述了此步骤。底部readme

    只需配置您的 webpack 以公开变量:

    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',
          },
       ...
    }
    

    然后像往常一样导入你的包。现在你可以在你的脚本标签代码中使用所有定义的变量了

    <script src="path/to/grpc.js"></script>
    <script> 
        const client = grpc.instantiateGreeterClient(...)
        ...
    </script>
    

    更多信息可以在webpack documentation找到

    【讨论】:

    • 鼓励链接到外部资源,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。
    猜你喜欢
    • 2020-07-20
    • 1970-01-01
    • 2020-10-23
    • 2020-09-29
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2013-01-15
    相关资源
    最近更新 更多