How to build individual component chunks with Vite to load with defineAsyncComponent

7.1k Views Asked by At

I'm not sure this is even possible, but it looks like some of the moving parts are there.

GOAL: Create a library of single file Vue 3 components that will compile into separate chunks using Vite, and be dynamically/async loaded at runtime. The app itself will load, then load up a directory of individually chunk'd elements to put in a toolbox, so afterward each element could be updated, and new ones could be added by putting new chunks in the same path.

So far, I can create the separate chunks within the vite.config as follows:

...
build: {
  rollupOptions: {
    output: {
      ...buildChunks()
    }
  }
}
...

The buildChunks function iterates over SFC files in the ./src/toolbox path and returns an object like...

{
  'toolbox/comp1':['./src/toolbox/comp1.vue'],
  'toolbox/comp2':['./src/toolbox/comp2.vue'],
  'toolbox/comp3':['./src/toolbox/comp3.vue'],
  ...
}

This all works, but I'm not sure how to make that next leap where the server code dynamically loads all of those generated chunk files without explicitly listing them in code. Also, since the Vite build adds an ID in the file name (e.g. comp.59677d29.js) on each build, referencing the actual file name in the import can't be done explicitly.

So far what I've considered is using defineAsyncComponent(()=>import(url)) to each of the files, but I'd need to generate a list of those files to import...which could be done by building a manifest file at build time, I guess.

Any suggestions? Is there a better approach?

0

There are 0 best solutions below