[英]File Structure: Requiring Sub-Modules in Node.js
I have the following Node.js module/npm package:我有以下 Node.js 模块/npm 包:
|- dist/
|- - requirejs/
|- - - [stuff in amd pattern ...]
|- - node/
|- - - index.js
|- - - submodules/
|- - - - submodule1.js
|- - - - [submodule2.js etc.]
|- package.json
|- README.md
I can require dist/node/index.js
via the module name (because I set it as the main entry-point file in package.json) like so:我可以通过模块名称要求
dist/node/index.js
(因为我将它设置为 package.json 中的主要入口点文件),如下所示:
var myModule = require('myModule');
I would like to require the submodule (as in AMD pattern) by doing so:我想通过这样做来要求子模块(如在 AMD 模式中):
var mySubmodule = require('myModule/submodules/submodule1');
This throws an error in Node.js.这会在 Node.js 中引发错误。 The problem is, that Node.js requires the main file from its
dist/node/
subdirectory but still keeps the modules root as the working directory.问题是,Node.js 需要其
dist/node/
子目录中的主文件,但仍将模块根目录作为工作目录。
Assuming the following structure would be present:假设存在以下结构:
|- dist/
|- - node/
|- - - index.js
|- submodules/
|- - submodule1.js
|- package.json
|- README.md
Now doing require('myModule/submodules/submodule1')
would work.现在做
require('myModule/submodules/submodule1')
会起作用。
NOW THE QUESTION: Is there any setting/config to set the "module namespace" or working directory to the directory where the main file is in, or do I really need to put the submodules folder into the project root, to make it accessible without doing require('myModule/dist/node/submodules/submodule1')
?现在的问题:是否有任何设置/配置可以将“模块命名空间”或工作目录设置为主文件所在的目录,或者我是否真的需要将子模块文件夹放入项目根目录中,以使其无需访问做
require('myModule/dist/node/submodules/submodule1')
吗?
Short answer: you can't.简短的回答:你不能。
Long answer: You should either directly use the second directory structure you proposed ( /myModule/submodules/
) or add some kind of API to your main exports ( index.js ) to quickly get the desired module.长答案:您应该直接使用您建议的第二个目录结构 (
/myModule/submodules/
) 或将某种 API 添加到您的主要导出 ( index.js ) 以快速获取所需的模块。
While you can technically call require('myModule/some/complex/path')
, the Node.js / npm packages standard is to rely on the unique interface provided by require('myModule')
.虽然技术上可以调用
require('myModule/some/complex/path')
,但 Node.js / npm 包标准依赖于require('myModule')
提供的唯一接口。
// /dist/node/index.js
var path = require('path');
exports.require = function (name) {
return require(path.join(__dirname, name));
};
Then in your app:然后在您的应用中:
var myModule = require('myModule');
var submodule1 = myModule.require('submodules/submodule1');
您现在可以使用 Node.js 的exports
功能执行类似操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.