創建項目
mkdir test-grpc
cd test-grpc
在test-grpc
目錄下創建以下文件,結構如下
├── src/ # 源代碼
│ ├── proto/ # Proto 文件
│ │ ├── greeter/ # Greeter gRPC service
│ │ │ └── greeter.proto
├── scripts/ # 腳本工具
│ └── protoc.sh # 根據proto文件生成 js/ts代碼腳本
└── ...
初始化項目、安裝相關包
npm init -y
npm install grpc google-protobuf dotenv
npm install typescript @types/node @types/google-protobuf @types/dotenv --save-dev
- grpc 用於gRPC與Node.js結合使用
- google-protobuf 用於javascript一起使用protobuf(.proto)
- dotenv從.env加載環境變量
編輯tsconfig
npx tsc --init
將以下內容添加到tsconfig.json文件中
{
"compilerOptions": {
"outDir": "./dist/",
"module": "commonjs",
"noImplicitAny": true,
"allowJs": true,
"esModuleInterop": true,
"target": "es6",
"sourceMap": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules"]
}
安裝代碼生成工具
npm install grpc-tools grpc_tools_node_protoc_ts --save-dev
- grpc-tools 爲原始文件.proto生成javascript文件
- grpc_tools_node_protoc_ts 根據grpc-tools生成的js代碼生成相應的d.ts代碼
創建腳本並執行
scripts/protoc.sh
#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
cd "${BASEDIR}"/../
PROTOC_GEN_TS_PATH="./node_modules/.bin/protoc-gen-ts"
GRPC_TOOLS_NODE_PROTOC_PLUGIN="./node_modules/.bin/grpc_tools_node_protoc_plugin"
GRPC_TOOLS_NODE_PROTOC="./node_modules/.bin/grpc_tools_node_protoc"
for f in ./src/proto/*; do
# skip the non proto files
if [ "$(basename "$f")" == "index.ts" ]; then
continue
fi
# loop over all the available proto files and compile them into respective dir
# JavaScript code generating
${GRPC_TOOLS_NODE_PROTOC} \
--js_out=import_style=commonjs,binary:"${f}" \
--grpc_out="${f}" \
--plugin=protoc-gen-grpc="${GRPC_TOOLS_NODE_PROTOC_PLUGIN}" \
-I "${f}" \
"${f}"/*.proto
${GRPC_TOOLS_NODE_PROTOC} \
--plugin=protoc-gen-ts="${PROTOC_GEN_TS_PATH}" \
--ts_out="${f}" \
-I "${f}" \
"${f}"/*.proto
done
授權
sudo chmod +x ./scripts/protoc.sh
執行腳本
./scripts/protoc.sh
會生成四個文件:一個pb、一個grpc_pb(並生成了相應的ts代碼)
src/proto/greeter
├── greeter.proto
├── greeter_grpc_pb.d.ts
├── greeter_grpc_pb.js
├── greeter_pb.d.ts
└── greeter_pb.js