Created
February 19, 2021 16:34
-
-
Save sciyoshi/34e5865f2523848f0d60b4cdd49382ee to your computer and use it in GitHub Desktop.
Esbuild plugin for compiling relay queries
This file contains 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
https://github.com/cometkim/vite-plugin-relay-lite
Here's for Vite