Skip to content

Instantly share code, notes, and snippets.

@sciyoshi
Created February 19, 2021 16:34
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save sciyoshi/34e5865f2523848f0d60b4cdd49382ee to your computer and use it in GitHub Desktop.
Save sciyoshi/34e5865f2523848f0d60b4cdd49382ee to your computer and use it in GitHub Desktop.
Esbuild plugin for compiling relay queries
import { promises } from "fs";
import crypto from "crypto";
import path from "path";
import { print, parse } from "graphql";
const plugin = {
name: "relay",
setup: build => {
build.onLoad({ filter: /\.tsx$/, namespace: "" }, async args => {
let contents = await promises.readFile(args.path, "utf8");
if (contents.includes("graphql`")) {
let imports = [];
contents = contents.replaceAll(/graphql`([\s\S]*?)`/gm, (match, query) => {
const formatted = print(parse(query));
const name = /(fragment|mutation|query) (\w+)/.exec(formatted)[2];
// const hash = crypto.createHash("md5").update(formatted, "utf8").digest("hex");
let id = `graphql__${crypto.randomBytes(10).toString("hex")}`;
imports.push(`import ${id} from "./__generated__/${name}.graphql.ts";`);
return id;
});
contents = imports.join("\n") + contents;
}
return {
contents: contents,
loader: "tsx",
};
});
},
};
@tony
Copy link

tony commented May 26, 2021

@sciyoshi Would love to see a demo project / repo with this!

@cometkim
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment