0

I can't figure out why the loadmodules function does not work? Tested on 2 different machines to rule out environment. Added snippet below and link to project on github for reproduction.

When I call the listModules function of Awilix it finds the functions fine, but not in the loadmodules function?

Trying to call resolve I get the error: "AwilixResolutionError: Could not resolve 'loginController'."

Please review snippet here

import { createContainer, asClass, asValue, asFunction, Lifetime, InjectionMode }  from 'awilix';
import awilix from 'awilix';
import loginController from './controllers/loginController.js'

const listModules = awilix.listModules;

const container = createContainer();

function setup() {

    const modulesToLoad = [
        ['controllers/**/*.js', Lifetime.SCOPED],
    ];

    // This does not work
    container.loadModules(modulesToLoad, {
        formatName: 'camelCase',
        resolverOptions: { register: asFunction },
        esModules: true // Loading ES modules
    });

    // This works
    // container.register({        
    //     loginController: awilix.asFunction(loginController)
    // })

    console.log(listModules(modulesToLoad))
    console.log(container.registrations)
    container.resolve('loginController')
}


export {
    container,
    setup
};

Link for project to reproduce: https://github.com/simonbinbox/AwilixTest

Simon
  • 3
  • 1

1 Answers1

0

I hit this same problem. SO frustrating. Turns out, your package.json (may not matter?) says it is a module and the awilix option for esModules is turned on:

Package.json:

  "type": "module",

Awilix config:

esModules: true // Loading ES modules

The awilix documentation says

When using opts.esModules, a Promise is returned due to using the asynchronous import().

The container.loadModules does work, it just doesn't work right away. You have to await for the promise it returns to complete. So change your load to be like the following to see registrations:

container.loadModules(modulesToLoad, {
    formatName: 'camelCase',
    resolverOptions: { register: asFunction },
    esModules: true // Loading ES modules
})
    .then(() => console.log(container.registrations));
Austin Haws
  • 364
  • 2
  • 6
  • 15
  • This worked. Thank you so much Austin. I had given up resolving this and basically just left it. – Simon Jun 29 '23 at 07:07