Install & access a local folder as a npm module

你说的曾经没有我的故事 提交于 2021-02-11 12:32:27

问题


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. So, I ran : yarn add "/var/www/main-folder/deploy-abc". It installed correctly & I can see the 'deploy-abc' dependency listed in package.json.

However, when I try to access the deploy-abc's exported object, I get node error Error: Cannot find module 'deploy-abc'. E.g: In some file in the main folder:

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

Where am I going wrong?


回答1:


As per the node docs: 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.

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:

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

You also don't need to specify the actual file in this case, as it defaults to index.js. If however the entry file was say, dabc.js or something else, you would need to also specify that in the location.




回答2:


You might have to use the exact relative path. For example, const deployAbc = require("../deploy-abc")



来源:https://stackoverflow.com/questions/50155052/install-access-a-local-folder-as-a-npm-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!