fix(server): support non-function exports from island files (#1986)

This commit is contained in:
Reed von Redwitz
2023-11-06 11:55:16 +01:00
committed by GitHub
parent 33cc4c7866
commit 8b846816a6
12 changed files with 67 additions and 18 deletions
+38 -7
View File
@@ -115,9 +115,44 @@ function toImportSpecifier(file: string) {
return specifier;
}
async function islandImportLine(
file: string,
i: number,
directory: string,
): Promise<string> {
const specifier = toImportSpecifier(file);
const moduleURL = new URL(`file://${directory}/${specifier}`);
const module = await import(moduleURL.href);
const entries = Object.entries(module);
const allExportsAreComponents = entries.every(
([, exportedEntity]) => typeof exportedEntity === "function",
);
// if all exports are components, we can use the simple, existing form
if (allExportsAreComponents) {
return `${JSON.stringify(specifier)}: $$${i},`;
}
// if not all exports are components, list the component exports explicitly
const componentExports = entries
.filter(([, exportedEntity]) => typeof exportedEntity === "function")
.map(([exportName]) => exportName);
const exportsString = componentExports
.map((exp) => `${exp}: $$${i}.${exp}`)
.join(", ");
return `"${specifier}": { ${exportsString} },`;
}
export async function generate(directory: string, manifest: Manifest) {
const { routes, islands } = manifest;
const islandImports = await Promise.all(
islands.map((file, i) => islandImportLine(file, i, directory)),
);
const output = `// DO NOT EDIT. This file is generated by Fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running \`dev.ts\`.
@@ -135,6 +170,7 @@ ${
)
.join("\n")
}
import { Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
@@ -146,15 +182,10 @@ const manifest = {
}
},
islands: {
${
islands.map((file, i) =>
`${JSON.stringify(`${toImportSpecifier(file)}`)}: $$${i},`
)
.join("\n ")
}
${islandImports.join("\n ")}
},
baseUrl: import.meta.url,
};
} satisfies Manifest;
export default manifest;
`;