JS_Reference.webp

From Scratch

The following steps are only necessary if you want to build everything from scratch!

To work with gRPC in Javascript, you need to install the google-protobuf and the grpc-web package. This is best done via the package.json file, assuming that you use npm.

{
  "version": "1.0.0",
  "name": "parametric-robot-control",
  "private": true,
  "dependencies": {
    "google-protobuf": "~3.21.4",
    "grpc-web": "~1.5.0"
  },
  "devDependencies": {
    "terser-webpack-plugin": "^5.3.10",
    "webpack": "~5.94.0",
    "webpack-cli": "~5.1.4"
  }
}

Create a webpack configuration as below.

const TerserPlugin = require("terser-webpack-plugin");
const path = require('path');

module.exports = {
    mode: "production",
    entry: "./export.js",
    devtool: "source-map",
    optimization: {
      minimize: false,
      minimizer: [
          new TerserPlugin({
              terserOptions: {
                  keep_classnames: true,
                  keep_fnames: true
              }
            })
          ]
    },
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'prc.js',
     globalObject: 'this',
     library: {
       name: 'prc',
       type: 'umd',
     },
    }
  };

Then you can automatically generate Javascript code with that command:

protoc -I=. prc.proto \
  --js_out=import_style=commonjs,binary:. \
  --grpc-web_out=import_style=commonjs,mode=grpcwebtext:.

This gets you the following files:

prc_grpc_web_pb.js

prc_pb.js

The exports.js file exports the relevant classes.

You can also generate Typescript files which will help with auto-completion, see here https://github.com/grpc/grpc-web?tab=readme-ov-file#typescript-support

Use the following commands to install the packages and create the prc.js file in the dist directory via webpack.

npm install
npx webpack

If you want to test it on a web server, you could run the following command