[英]NPM dependency that imports/requires from the app's root
Let's say I create an app called App
. 假设我创建了一个名为
App
的应用App
。 It installs an npm dependency called package
. 它安装了一个名为
package
的npm依赖项。
Now let's say package
requires that App
has the following file structure: 现在,假设
package
要求App
具有以下文件结构:
Within App/node_modules/package/index.js
, it needs to import/require the file located at App/folder/file.js
. 在
App/node_modules/package/index.js
,它需要导入/获取位于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 包/ index.js
let File = null;
function init (fileModule) {
File = fileModule;
}
export init;
// ...
This way you can pass the File
object from your main app: 这样,您可以从主应用程序传递
File
对象:
App/index.js 应用/ 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. 您将如何设计API以传递“中间件”。 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. 实际上,这就是Express等框架的工作方式。 It allows Express to be extended without it knowing the structure of your code:
它允许Express在不知道代码结构的情况下进行扩展:
app.use(someMiddleware); // Express never "requires" your middleware
// instead it allows you to pass middleware to itself
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.