javascriptvuexvuex-orm

Loop Javascript Imports to load into VuexORM


Anytime I have a long list of items to import in javascript my natural intention is to export those items in a separate file, require that file in my main javascript file, then if they need to be loaded into Vue or some other process, loop through them and load them dynamically.

I'm just getting started with VueORM, and ORM Models need to be loaded into the VueORM instance like so:

import Foo from '@/models/foo'
import Bar from '@/models/bar'

database.register(Foo)
database.register(Bar)

My app will have dozens of models so I'd like to export those from a single file as I mentioned, then loop through them and register them.

// main.js


import * as models from '@/models'

Object.keys(models).forEach(key => {
    database.register(model[key])
})

In my models I'm exporting each as a function like so:

// models/index.js


export const Foo = () => import('@models/foo')
export const Bar = () => import('@models/bar')

This normally works fine, but in VuexORM the models are not being loaded.

Can someone please advise on a better method to load these Models from a separate file?


Solution

  • Vuex ORM does not handle dynamic imports. Rather than export them as dynamic imports, simply export them using the ordinary ESM syntax?

    The following assumes your models are default exports.

    // models/index.js
    
    export { default as Foo } from '@/models/foo'
    export { default as Bar } from '@/models/bar'
    

    Subsequently, your main.js can aggregate the modules:

    // main.js
    
    import * as models from '@/models'
    
    Object.values(models).forEach(model => database.register(model))