0

I am writing a framework package which I'd like to make it able to auto require modules from the main projects src/. If you are familiar with rails, this is akin to its autoload feature.

So if in your web app you follow a directory convention, say src/models/my-model.js, then the framework can require the my-model module on its own. The framework, which is a dependency of the web app, only need know the name of the relation (ie "todos") in order to require the model (ie. src/models/todo.js)

I've tried adding my web apps src directory in my web apps webpack chain config.resolve.modules.add(path.resolve(__dirname, 'src')) but it does not seem to apply to the search paths for dependencies (not sure) so my framework lib still can't find modules in my web app.

I've also (desperately) tried passing require from the web app to the dependency and then in the dependency code I call var MyModel = this.thePassedInRequireFn("./models/" + modelName), but it errors:

(`Uncaught Error: Cannot find module './models/my-model'
    at MyFramework.webpackEmptyContext

Anybody have ideas how this can be done?

If the solution can be independent of the use of webpack, that would be ideal, but webpack compatibility is what is most important to me.

btd
  • 404
  • 3
  • 12

1 Answers1

0

Here is a webpack specific answer using require.context().

https://webpack.js.org/guides/dependency-management/#require-context

In the web app create a require context. For example:

const requireModule = require.context('./models/', true);

Then pass requireModule to the framework you have as a dependency of your web app.

If your web app has a model in the file ./models/todo-item.js and the framework is given the models name todoItem, the framework can require it using only the model name like so:

let fileName = `./${kebabCase(modelName)}`;
let module = this.requireModule(fileName).default;
btd
  • 404
  • 3
  • 12