简体   繁体   English

安装并访问本地文件夹作为npm模块

[英]Install & access a local folder as a npm module

The file structure looks like this: 文件结构如下所示:

= (main-folder)
 - package.json
 - ...
 = server
  - index.js
  - ...
 = deploy-abc // new server
  = src
   - index.js
 = src
  - index.js
  - ...

I am trying to install 'deploy-abc' as a module within the main-folder app. 我正在尝试在主文件夹应用程序中将'deploy-abc'安装为模块。 So, I ran : yarn add "/var/www/main-folder/deploy-abc" . 所以,我跑了: yarn add "/var/www/main-folder/deploy-abc" It installed correctly & I can see the 'deploy-abc' dependency listed in package.json. 它安装正确,我可以在package.json中看到“ deploy-abc”依赖项。

However, when I try to access the deploy-abc's exported object, I get node error Error: Cannot find module 'deploy-abc' . 但是,当我尝试访问deploy-abc的导出对象时,出现节点错误Error: Cannot find module 'deploy-abc' Eg: In some file in the main folder: 例如:在主文件夹中的某个文件中:

const deployAbc = require("deploy-abc");
console.log(deployAbc); // error

Where am I going wrong? 我要去哪里错了?

As per the node docs: https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders 根据节点文档: https : //nodejs.org/api/modules.html#modules_loading_from_node_modules_folders

If the module identifier passed to require() is not a core module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location. 如果传递给require()的模块标识符不是核心模块,并且不是以'/'、'../'或'./'开头,则Node.js从当前模块的父目录开始,并添加/ node_modules,然后尝试从该位置加载模块。

So, seeing as your module is now in the main folder, how you require it will depend on the relative location. 因此,看到您的模块现在位于主文件夹中,您对模块的要求将取决于相对位置。 If you are requiring it from say /src/index.js , then you will need: 如果您需要从/src/index.js它,那么您将需要:

const deployAbc = require('../deploy-abc')

You also don't need to specify the actual file in this case, as it defaults to index.js . 在这种情况下,您也无需指定实际文件,因为它默认为index.js If however the entry file was say, dabc.js or something else, you would need to also specify that in the location. 但是,如果输入文件是dabc.js或其他内容,则还需要在该位置中指定该文件。

You might have to use the exact relative path. 您可能必须使用确切的相对路径。 For example, const deployAbc = require("../deploy-abc") 例如, const deployAbc = require("../deploy-abc")

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

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