index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import fs from "node:fs/promises";
  2. import path from "path";
  3. import {constants} from "node:fs";
  4. import parseComponent from "./parseComponent.js";
  5. export default async (express, options)=>{
  6. let opts = {
  7. production: true,
  8. routesDir: "routes",
  9. assetsDir: "assets"
  10. };
  11. Object.assign(opts, options)
  12. let app = express();
  13. console.time("Build time");
  14. await fs.rm(path.join(process.cwd(), ".build/"), {recursive: true, force: true});
  15. let root = path.join(process.cwd(), opts.routesDir);
  16. await addRoute(root, root, app, opts);
  17. app.use(`/${opts.assetsDir}`, express.static(opts.assetsDir));
  18. console.timeEnd("Build time");
  19. return app;
  20. }
  21. const addRoute = async (dir, root, app, opts)=>{
  22. const files = await fs.readdir(dir, {withFileTypes: true});
  23. const indexFile = await findIndexFile(dir);
  24. if(!indexFile) return;
  25. let route = dir.replace(root, "");
  26. route = route === "" ? "/" : route;
  27. if(opts.production){
  28. const bundle = await parseComponent(indexFile);
  29. const bundleLocation = dir.replace(opts.routesDir, "build");
  30. const htmlPath = path.join(bundleLocation, "index.html");
  31. await fs.mkdir(bundleLocation, {recursive: true});
  32. await fs.writeFile(htmlPath, bundle);
  33. app.get(route, async (req, res)=>{res.sendFile(htmlPath)});
  34. }else{
  35. app.get(route, async (req, res)=>{res.send(await parseComponent(indexFile))});
  36. }
  37. fs.rm(path.join(dir, "tmp/"), {recursive: true, force: true});
  38. for(let i = 0; i < files.length; i++){
  39. const curDir = path.join(dir, files[i].name);
  40. if(files[i].isDirectory()) {
  41. await addRoute(curDir, root, app, opts);
  42. }
  43. }
  44. }
  45. const findIndexFile = async (dir)=>{
  46. const neovanPath = path.join(dir, "index.neovan");
  47. const htmlPath = path.join(dir, "index.html");
  48. const [neovan, html] = await Promise.allSettled([
  49. fs.access(path.join(dir, "index.neovan"), constants.F_OK),
  50. fs.access(path.join(dir, "index.html"), constants.F_OK)
  51. ]);
  52. if(neovan.status === "fulfilled") return neovanPath;
  53. if(html.status === "fulfilled") return htmlPath;
  54. return null;
  55. }