GrpcToolsNodeProtocPlugin.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Compiler } from 'webpack';
  2. const grpcTools = require('grpc-tools');
  3. const { execSync } = require('child_process');
  4. const path = require('path');
  5. const fs = require('fs');
  6. const glob = require('glob');
  7. function clearOutputDirectory(directory:string) {
  8. if (fs.existsSync(directory)) {
  9. const files = fs.readdirSync(directory);
  10. for (const file of files) {
  11. const filePath = path.join(directory, file);
  12. fs.unlinkSync(filePath);
  13. }
  14. }
  15. }
  16. export = GrpcToolsNodeProtocPlugin;
  17. // Define the interface for the plugin options
  18. interface GrpcToolsNodeProtocPluginOptions {
  19. protoPaths?: string[];
  20. protoSources?: string[];
  21. outputDir?: string;
  22. }
  23. class GrpcToolsNodeProtocPlugin {
  24. private protoPaths: string[];
  25. private protoSources: string[];
  26. private outputDir: string;
  27. constructor(options: GrpcToolsNodeProtocPluginOptions) {
  28. this.protoPaths = options.protoPaths || []; // Array of proto_path directories
  29. this.protoSources = options.protoSources || []; // Array of proto source files or directories
  30. this.outputDir = options.outputDir || './'; // Output directory
  31. }
  32. apply(compiler:Compiler) {
  33. compiler.hooks.environment.tap('GrpcToolsNodeProtocPlugin', () => {
  34. try {
  35. console.log(`Cleaning existing files, if any`)
  36. clearOutputDirectory(this.outputDir);
  37. console.log(`Writing protocol buffer files into ${this.outputDir}`)
  38. // Resolve proto_path directories
  39. const resolvedProtoPaths = this.protoPaths.map(p => path.resolve(__dirname, p));
  40. var resolvedProtoSources:string[] = [];
  41. this.protoSources.forEach(function (s) {
  42. var matches = glob.sync(path.resolve(__dirname, s));
  43. resolvedProtoSources = resolvedProtoSources.concat(matches);
  44. });
  45. const protocArgs = [
  46. `--js_out=import_style=commonjs,binary:${this.outputDir}`,
  47. // `--grpc_out=generate_package_definition:${this.outputDir}`,
  48. ...resolvedProtoPaths.map(p => `--proto_path=${p}`),
  49. ...resolvedProtoSources
  50. ];
  51. const command = `npx grpc_tools_node_protoc ${protocArgs.join(' ')}`;
  52. execSync(command, { stdio: 'inherit' });
  53. } catch (error) {
  54. console.error('Error running grpc tools', error);
  55. }
  56. });
  57. }
  58. }