From ef3377ec7d335fc57204ea825c39a6d87bbc570b Mon Sep 17 00:00:00 2001 From: Ayo Date: Sun, 8 Oct 2023 09:20:38 +0200 Subject: [PATCH] test output directory --- plugins/1-copy-components.ts | 11 +++++++++++ plugins/2-register-components.ts | 29 +++++++++++++++++++++++++++++ routes/[...index].ts | 2 +- 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 plugins/1-copy-components.ts create mode 100644 plugins/2-register-components.ts diff --git a/plugins/1-copy-components.ts b/plugins/1-copy-components.ts new file mode 100644 index 0000000..cec744c --- /dev/null +++ b/plugins/1-copy-components.ts @@ -0,0 +1,11 @@ +import * as fs from "fs"; +export default defineNitroPlugin(async () => { + console.log("Copying components to public folder..."); + const rawKeys = await useStorage().getKeys("/assets/components"); + rawKeys.forEach(async (key) => { + const cleanKey = key.replace("assets:components:", ""); + const content = await useStorage().getItem(key); + if (!fs.existsSync("./public/output")) fs.mkdirSync("./public/output"); + fs.writeFileSync(`./public/output/${cleanKey}`, content.toString()); + }); +}); diff --git a/plugins/2-register-components.ts b/plugins/2-register-components.ts new file mode 100644 index 0000000..487ab86 --- /dev/null +++ b/plugins/2-register-components.ts @@ -0,0 +1,29 @@ +import * as fs from "fs"; + +export default defineNitroPlugin(async () => { + console.log("Building registry of custom elements..."); + const rawKeys = await useStorage().getKeys("/assets/components"); + const keys = rawKeys.map((key) => key.replace("assets:components:", "")); + console.log("Found components:", keys); + const imports = keys.map((key, index) => { + return `import C${index} from "./${key}"`; + }); + + const registryObject = `const registry = { + ${keys + .map((key, index) => { + const name = key.replace(".js", "").replace(".ts", ""); + return `"${name}": C${index}`; + }) + .join(",")}}`; + + const customElementsDefine = `Object.keys(registry).forEach((key) => {if(window?.hasOwnProperty("customElements"))customElements.define(key, registry[key]);})`; + + if (!fs.existsSync("./public/output")) { + fs.mkdirSync("./public/output"); + } + fs.writeFileSync( + "./public/output/registry.js", + [...imports, registryObject, customElementsDefine].join(";") + ); +}); diff --git a/routes/[...index].ts b/routes/[...index].ts index 14c9c53..fce3126 100644 --- a/routes/[...index].ts +++ b/routes/[...index].ts @@ -12,7 +12,7 @@ export default eventHandler(async (event) => { // temporary; use ultrahtml later const registryScript = - ''; + ''; html = html.toString().replace("", registryScript + ""); return html ?? new Response("Not found", { status: 404 });