-
-
Save asvny/12d2cc0aaf9732754c7fc2d8a3893a6f to your computer and use it in GitHub Desktop.
Esbuild plugin for compiling relay queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | |
}; | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment