Xavier Geerinck Xavier Geerinck - 2 months ago 9
Node.js Question

How can I pass a library to a lower dependency in node?

I'm trying to create a library that uses the ORM Bookshelf.js (so basically a wrapper on top of Bookshelf.js if you will). Now Bookshelf.js requires you to run a driver installation to be able to connect to the correct database (such as:

npm install mysql
) in the root of your project.

My own library also requires this, since Bookshelf.js requires it, but it keeps saying
Error: Cannot find module 'mysql'
which is normal since the Bookshelf instance does not have the mysql dependency in its node_modules folder.

If I type out the structure it would look like this:

* New Project
** mysql
** LibThatUsesBookshelf
**** Bookshelf


Now Bookshelf.js probably requires this structure:

* New Project
** LibThatUsesBookshelf
**** mysql
**** Bookshelf


Is there a way that I am able to still get bookshelf working with the first structure shown?

P.S. I know the explanation might be confusing, but it is a hard problem and I got no other way of explaining it.

Answer

Let the client of your module pass in an instance to bookshelf:

// mysuperfancymodule.js
module.exports = function(bookshelf) {
    // do fancy things with the bookshelf instance
}

Then in your client application:

// some app code:
var mySuperFancyModule = require('mysuperfancymodule'); // assuming it is published to npm
var knex = require('knex')({
    // init knex...
});
var bookshelf = require('bookshelf')(knex);

mySuperFancyModule(bookshelf); // init my super fancy module