Skip to content

Instantly share code, notes, and snippets.

@istarkov
Last active March 3, 2022 01:20
Show Gist options
  • Save istarkov/30ab1b7f88c068e8f72e99c32e14877b to your computer and use it in GitHub Desktop.
Save istarkov/30ab1b7f88c068e8f72e99c32e14877b to your computer and use it in GitHub Desktop.
Fast and dirty rollup relay plugin (for use in vite + sveltekit)
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function relay() {
return {
name: 'relay',
transform(code) {
// Use indexOf as its probably ;-) faster
if (code.indexOf('graphql`') > -1) {
const re = /graphql`[^`]+(?<type>query|fragment|mutation)\s+(?<name>[\w_-\d]+)[^`]+`/gm;
let imports = [];
let transformedCode = code.replace(re, (matchStr, _g1, _g2, _pos, _code, groups) => {
if (groups.type === 'query') {
const importName = `__graphql__${groups.name}__`;
imports.push(
`import ${importName} from '$lib/__generated__/${groups.name}.graphql.ts';`
);
return importName;
}
// For now we dont support mutations, as we dont use them in svelte project
// Convert to null preseving lines for sourcemaps to work
return `null /*${matchStr}*/`;
});
if (imports.length > 0) {
transformedCode += `
${imports.join('\n')}
`;
}
return { code: transformedCode };
}
return null;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment