vite-plugin-gql-tada.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { generateOutput } from '@gql.tada/cli-utils';
  2. import * as fs from 'fs/promises';
  3. import { printSchema } from 'graphql';
  4. import * as path from 'path';
  5. import { Plugin } from 'vite';
  6. import { generateSchema } from './utils/schema-generator.js';
  7. import { ConfigLoaderApi, getConfigLoaderApi } from './vite-plugin-config-loader.js';
  8. export function gqlTadaPlugin(options: {
  9. gqlTadaOutputPath: string;
  10. tempDir: string;
  11. packageRoot: string;
  12. }): Plugin {
  13. let configLoaderApi: ConfigLoaderApi;
  14. return {
  15. name: 'vendure:gql-tada',
  16. configResolved({ plugins }) {
  17. configLoaderApi = getConfigLoaderApi(plugins);
  18. },
  19. async buildStart() {
  20. const { vendureConfig } = await configLoaderApi.getVendureConfig();
  21. const safeSchema = await generateSchema({ vendureConfig });
  22. const tsConfigContent = {
  23. compilerOptions: {
  24. plugins: [
  25. {
  26. name: 'gql.tada/ts-plugin',
  27. schema: './schema.graphql',
  28. },
  29. ],
  30. },
  31. };
  32. const tsConfigPath = path.join(options.tempDir, 'tsconfig.json');
  33. await fs.writeFile(tsConfigPath, JSON.stringify(tsConfigContent, null, 2));
  34. const schemaPath = path.join(options.tempDir, 'schema.graphql');
  35. await fs.writeFile(schemaPath, printSchema(safeSchema));
  36. await generateOutput({
  37. output: path.join(options.gqlTadaOutputPath, 'graphql-env.d.ts'),
  38. tsconfig: tsConfigPath,
  39. });
  40. // Copy the graphql.ts file to the output path
  41. const graphqlTsPath = path.join(options.packageRoot, 'src/lib/graphql/graphql.ts');
  42. try {
  43. await fs.copyFile(graphqlTsPath, path.join(options.gqlTadaOutputPath, 'graphql.ts'));
  44. } catch (error) {
  45. if (error instanceof Error) {
  46. this.error(error.message);
  47. } else {
  48. this.error('Failed to copy graphql.ts file');
  49. }
  50. }
  51. this.info('graphql introspection files output to ' + options.gqlTadaOutputPath);
  52. },
  53. };
  54. }