GrpcToolsNodeProtocPlugin.ts 2.7 KB

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