imports/requires 来自应用根目录的 NPM 依赖

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

假设我创建了一个名为 App 的应用程序。它安装了一个名为 package.

的 npm 依赖项

现在假设 package 要求 App 具有以下文件结构:

App/node_modules/package/index.js内,它需要import/require位于App/folder/file.js的文件。

例如:

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

这是最好的方法吗?有什么方法可以在导入中引用应用程序的根而不需要使用 ../../?

没有。这不是最好的方法。模块不应该要求他们的用户。

改为使用依赖项注入 - 让您的用户将您需要的对象传递给您:

package/index.js

let File = null;

function init (fileModule) {
    File = fileModule;
}

export init;

// ...

这样您就可以从您的主应用传递 File 对象:

App/index.js

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

init(File);

如何设计 API 来传递 "middleware" 取决于您。以上只是一个建议。您可以将其作为参数传递给构造函数,例如:

const package = new Package(File);

这实际上就是像 Express 这样的框架的工作原理。它允许在不知道代码结构的情况下扩展 Express:

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