简体   繁体   English

无法在下游 node_modules 中使用“require”

[英]Unable to use 'require' in downstream node_modules

I am developing an express api, where routes are installed as a dependency of the main project.我正在开发一个 express api,其中路由作为主项目的依赖项安装。 Inside the main project I have a config folder with index.js.在主项目中,我有一个带有 index.js 的配置文件夹。 index.js is exporting an object that serves as the route configuration. index.js 正在导出一个 object 作为路由配置。

Inside the main project, I am able to get inside this exported object from all of the files, however, when trying to require from this config object inside of the node_modules dependency, it is coming back as undefined.在主项目中,我可以从所有文件中获取这个导出的 object,但是,当尝试从 node_modules 依赖项中的这个配置 object 中请求时,它会以未定义的形式返回。 I have tried with both relative and absolute pathnames in the require statement and neither seem to retrieve the js object.我在require语句中尝试了相对路径名和绝对路径名,似乎都没有检索到js object。

using commonJs.使用 commonJs。 Confirmed that I am using module.exports and require statements on the receiving end.确认我在接收端使用 module.exports 和 require 语句。 Tried require statement from app.js and include a module.exports statement there as well.尝试了 app.js 中的 require 语句,并在那里包含了一个 module.exports 语句。 No luck.没运气。

Is there some magical way to get objects exported from the main project into the dependency packages?是否有一些神奇的方法可以将对象从主项目导出到依赖包中? Wondering if there is something simple I am missing.想知道我是否缺少一些简单的东西。

 Structure: -app.js (main) -package.json --routes (folder) | index.js ('imports' route express modules from node_modules) --config (folder) | index.js (where module.exports.objectname = {stuff:stuff} exists) --node_modules | packagefolder (project scope) | packagename (route scope) | functions (folder) bunchofjs files to complete i/o of requests routes (folder) index.js (package.json main. Handles require from../../..) config (folder) index.js (where the config require statement is.)

Sample statement from main application in the config/index.js: config/index.js 中主应用程序的示例语句:

 const globalConfig = { port: 4443, otherinfo: "stuff" } module.exports.globalConfig = globalConfig

Sample code from inside node_modules/packagefolder/packagename/routes/index.js node_modules/packagefolder/packagename/routes/index.js 内部的示例代码

 const port = require('../../../../../config').globalConfig.port

Sample error:示例错误:

 TypeError: Cannot read properties of undefined

The carrot( ^ ) symbol is on the dot between globalConfig and port.胡萝卜( ^ ) 符号位于 globalConfig 和端口之间的点上。

Answer attributed from @bigless in comments.来自@bigless 在评论中的答案。 Having dependency packages reach outside of the node_modules folder would be considered a security risk and is blocked by design.让依赖包到达 node_modules 文件夹之外将被视为安全风险,并被设计阻止。 The strategy of the app using configs needs to be redesigned to keep this in mind.需要重新设计应用程序使用配置的策略以牢记这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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