简体   繁体   中英

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:

  • App/
    • node_modules/
      • package/
        • index.js
        • package.json
    • folder/
      • file.js
    • index.js
    • package.json

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 ../../ ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM