Jake
Jake

Reputation: 4255

NPM dependency that imports/requires from the app's root

Let's say I create an app called App. It installs an npm dependency called package.

Now let's say package requires that App has the following file structure:

Within App/node_modules/package/index.js, it needs to import/require the file located at App/folder/file.js.

For example:

import File from "../../folder/file";

Is this the best way to do this? Is there any way I can reference the App's root in the import instead of needing to use ../../?

Upvotes: 0

Views: 252

Answers (1)

slebetman
slebetman

Reputation: 113906

No. This is not the best way to do it. Modules should not require from their users.

Use dependency injection instead - let your user pass you the objects you require:

package/index.js

let File = null;

function init (fileModule) {
    File = fileModule;
}

export init;

// ...

This way you can pass the File object from your main app:

App/index.js

import { init } from 'package';
import File from './folder/file';

init(File);

How you design the API to pass your "middleware" is up to you. The above is just a suggestion. You can pass it as an argument to a constructor for example:

const package = new Package(File);

This is in fact how frameworks like Express works. It allows Express to be extended without it knowing the structure of your code:

app.use(someMiddleware); // Express never "requires" your middleware
                         // instead it allows you to pass middleware to itself

Upvotes: 1

Related Questions