English | 简体中文
注意: 请确保系统上已装有 protoc
和 protoc-gen-grpc-web
。
npm i --save-dev grpc-webpack-plugin
yarn add --dev grpc-webpack-plugin
webpack.config.js
const GrpcWebPlugin = require('grpc-webpack-plugin');
const path = require('path');
const DIR = path.resolve(__dirname, './protos');
const OUT_DIR = path.resolve(__dirname, './generated');
module.exports = {
mode: 'development',
plugins: [
// Proto messages
new GrpcWebPlugin({
protoPath: DIR,
protoFiles: ['echo.proto'],
outputType: 'js',
importStyle: 'commonjs',
binary: true,
outDir: OUT_DIR,
}),
// Service client stub
new GrpcWebPlugin({
protoPath: DIR,
protoFiles: ['echo.proto'],
outputType: 'grpc-web',
importStyle: 'commonjs+dts',
mode: 'grpcwebtext',
outDir: OUT_DIR,
}),
],
// 另外,你可以添加如下配置来调试你的插件参数
// 需要 webpack 的版本不低于 v4.37
infrastructureLogging: {
level: 'error',
debug: /GrpcWebPlugin/,
},
});
选项名 | 描述 | 类型 | 默认值 |
---|---|---|---|
protoPath |
必填,例:'./protos' |
{String} |
|
protoFiles |
必填,例:['foo.proto', 'bar.proto'] |
{Array.<string>} |
|
outputType |
必填,例:'js' | 'grpc-web' |
{String} |
|
importStyle |
'closure' | 'commonjs' | 'commonjs+dts' | 'typescript' ,详见 Import Style |
{String} |
'closure' |
binary |
开启此选项可序列化/反序列化二进制格式的 proto | {Boolean} |
false |
mode |
'grpcwebtext' | 'grpcweb' ,详见 Wire Format Mode |
{String} |
'grpcwebtext' |
outDir |
{String} |
'.' |
|
extra |
其他编译参数,详见 protoc -h |
{Array.<string>} |
[] |
synchronize |
使你的 pb 生成代码与 .proto 中的定义保持同步,将其设为 false 即可使 pb 文件只读 |
{Boolean} |
true |
watch |
监听 .proto 文件,在其更改时重新编译之,仅在 synchronize 为 true 时生效。(需要打开 webpack 的监听模式) |
{Boolean} |
true |
注意: commonjs+dts
和 typescript
仅适用于 outputType 为 grpc-web
的情况。