Skip to content

Commit 54120e4

Browse files
committed
build: Add build plugins to handle imports of GraphQL queries and Handlebars templates
1 parent 3c940a2 commit 54120e4

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

scripts/build.ts

+57-1
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,58 @@ export const InlineSqlBunPlugin: BunPlugin = {
9191
},
9292
};
9393

94+
export const InlineGraphQlBunPlugin: BunPlugin = {
95+
name: "inline-graphql",
96+
setup(builder) {
97+
// Hook into the "resolve" phase to intercept .gql imports
98+
builder.onResolve({ filter: /\.gql$/ }, async (args) => {
99+
// Resolve the .gql file path relative to the directory of the importing file
100+
const resolvedPath = Bun.resolveSync(
101+
args.path,
102+
path.dirname(args.importer),
103+
);
104+
return { path: resolvedPath, namespace: "graphql" };
105+
});
106+
107+
// Handle the .gql file loading
108+
builder.onLoad(
109+
{ filter: /\.gql$/, namespace: "graphql" },
110+
async (args) => {
111+
const graphQlQueryFileContent = await Bun.file(
112+
args.path,
113+
).text();
114+
const contents = `const graphQlQuery = \`${graphQlQueryFileContent}\`;
115+
export default graphQlQuery;`;
116+
return { contents, loader: "js" };
117+
},
118+
);
119+
},
120+
};
121+
122+
export const CompiledHandlebarsTemplateBunPlugin: BunPlugin = {
123+
name: "compile-handlebars",
124+
setup(builder) {
125+
builder.onResolve({ filter: /\.hbs$/ }, async (args) => {
126+
const resolvedPath = Bun.resolveSync(
127+
args.path,
128+
path.dirname(args.importer),
129+
);
130+
return { path: resolvedPath, namespace: "handlebars" };
131+
});
132+
133+
builder.onLoad(
134+
{ filter: /\.hbs$/, namespace: "handlebars" },
135+
async (args) => {
136+
const handlebarsFileContent = await Bun.file(args.path).text();
137+
const contents = `import Handlebars from "handlebars";
138+
const graphQlQuery = Handlebars.compile(\`${handlebarsFileContent}\`, { strict: true });
139+
export default graphQlQuery;`;
140+
return { contents, loader: "js" };
141+
},
142+
);
143+
},
144+
};
145+
94146
export interface WasmBuildConfig {
95147
target: "bundler" | "nodejs" | "web" | "no-modules" | "deno";
96148
path: string;
@@ -144,7 +196,11 @@ export interface BuildConfig {
144196
sourcemap: boolean;
145197
}
146198

147-
const defaultBunPlugins = [InlineSqlBunPlugin];
199+
const defaultBunPlugins = [
200+
InlineSqlBunPlugin,
201+
InlineGraphQlBunPlugin,
202+
CompiledHandlebarsTemplateBunPlugin,
203+
];
148204

149205
export function build(config: BuildConfig) {
150206
const createOutputFolder = ResultAsync.fromPromise(

0 commit comments

Comments
 (0)