#Bundle TS file from FileSystemRouter into the compiled executable

1 messages · Page 1 of 1 (latest)

past knot
#

Hi there,

Is there a way to bundle my pages retrieved by FileSystemRouter at compile time in the compiled executable ?

I tried with Macro, but can't work because of promises :

// file -> /src/server.tsx
import { bundledRouter } from './utils/bundledRouter' with { type: 'macro' }

bundledRouter().then(([router, routes]) => {
  console.log(router)
})
// file -> /src/utils/bundledRouter.ts
export async function bundledRouter() {
  const router = new Bun.FileSystemRouter({
    style: "nextjs",
    dir: "./src/pages/",
    assetPrefix: "/static/"
  })

  const routes = Object.entries(router.routes).reduce<any>(async (acc, [key, value]) => {
    return {...(await acc), [key]: await import(value)}
  }, {});
  return await Promise.all(routes)
}
#

Which output only :

$ bun --hot src/server.tsx
 7 |   })
 8 | 
 9 |   const routes = Object.entries(router.routes).reduce<any>(async (acc, [key, value]) => {
10 |     return {...(await acc), [key]: await import(value)}
11 |   }, {});
12 |   return await Promise.all(routes)
                         ^
TypeError: undefined is not a function
      at all (:1:21)
      at src/utils/bundledRouter.ts:12:16
      at bundledRouter (src/utils/bundledRouter.ts:2:36)
      at requestFetch (:1:21)
      at requestInstantiate (:1:21)
      at requestSatisfyUtil (:1:21)
 7 |   })
 8 | 
 9 |   const routes = Object.entries(router.routes).reduce<any>(async (acc, [key, value]) => {
10 |     return {...(await acc), [key]: await import(value)}
11 |   }, {});
12 |   return await Promise.all(routes)
                         ^
TypeError: undefined is not a function
      at all (:1:21)
      at src/utils/bundledRouter.ts:12:16
      at bundledRouter (src/utils/bundledRouter.ts:2:36)
      at requestFetch (:1:21)
      at requestInstantiate (:1:21)
      at requestSatisfyUtil (:1:21)
18 | bundledRouter().then(([router, routes]) => {
     ^
error: macro threw exception
    at src/server.tsx:18:1
#

Here my files I want to have bundled :

$ tree src/pages/
src/pages/
├── error.tsx
├── index.tsx
├── room
│   ├── [room]
│   │   └── settings.tsx
│   └── [room].tsx
└── room.tsx

2 directories, 5 files
subtle palm
#

you can write a custom importer as a bun plugin

#

Where you bascially have a script that returns javascript/typescript code as a string. After execution of that string it could return the array you have right now as promise.

#

a very crude example could be

return `module.exports={${Object.entries(router.routes).map((route) => {return `${route.key}: await import(${route.value})`}).join()} }