問題描述
如何在客戶端排除導入 (How to exclude an import on client side)
我正在使用 protoc‑gen‑validate,這是一個代碼生成器用於在服務器端驗證 protobufs 的插件。服務器是用 Go 編寫的,但客戶端是用 Javascript 編寫的。我遇到的問題是 protoc‑gen‑validate
庫似乎包含在使用 ts‑protoc‑gen,這是一種 protoc‑gen‑validate
不受支持的語言。結果,使用生成的 javascript 代碼時出現 MODULE_NOT_FOUND
錯誤,此處失敗:
internal/modules/cjs/loader.js:1033
throw err;
^
Error: Cannot find module '../../validate/validate_pb.js'
Require stack:
‑ /home/amadeus/HarmonyProject/harmony‑grpc‑test/gen/core/v1/core_pb.js
‑ /home/amadeus/HarmonyProject/harmony‑grpc‑test/index.js
我願意想知道,如何自動從生成的代碼中排除這種導入?此外,如果解決方案保持 proto 文件不可變,那就太好了,因為它們位於 git 子模塊中。
參考解法
方法 1:
Messy hack to fix this, looking for more elegant ways to make this work:
IN_DIR="./protocol"
PROTOCOL_BUILD_TMP="./protocol‑build‑tmp"
mkdir ‑p $PROTOCOL_BUILD_TMP
cp ‑r $IN_DIR $PROTOCOL_BUILD_TMP
for dir in $(find "${PROTOCOL_BUILD_TMP}" ‑name '*.proto' ‑print0 | xargs ‑0 ‑n1 dirname | sort | uniq); do
sed ‑i ‑E "s/ \[ \(validate.rules(.*)\];/;/g" $(find "${dir}" ‑name '*.proto')
sed ‑i ‑E "/validate.proto/d" $(find "${dir}" ‑name '*.proto')
done
rm ‑r $PROTOCOL_BUILD_TMP
方法 2:
This is also a messy hack but it works.
Create a validate_pb.js
file along with the generated files and paste the following code in it.
var jspb = require('google‑protobuf');
var goog = jspb;
var global = (function() {
if (this) { return this; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
if (typeof self !== 'undefined') { return self; }
return Function('return this')();
}.call(null));
goog.exportSymbol('proto.tagger', null, global);
This solved the issue for me.
(by Bluskript、Bluskript、Chandraaditya)