安装与安装将本地文件夹作为npm模块访问 [英] Install & access a local folder as a npm module

查看:80
本文介绍了安装与安装将本地文件夹作为npm模块访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件结构如下:

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

我正在尝试将'deploy-abc'作为模块安装在主文件夹应用程序中.因此,我运行了: yarn add"/var/www/main-folder/deploy-abc" .它已正确安装&我可以在package.json中看到"deploy-abc"依赖项.

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.

但是,当我尝试访问deploy-abc的导出对象时,出现节点错误错误:找不到模块'deploy-abc'.例如:在主文件夹中的某个文件中:

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

我要去哪里错了?

推荐答案

根据节点文档: https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders

如果传递给require()的模块标识符不是核心模块,并且不是以'/'、'../'或'./'开头,则Node.js从以下位置开始:当前模块,并添加/node_modules,然后尝试从该位置加载该模块.

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.

因此,看到您的模块现在位于主文件夹中,您对它的要求将取决于相对位置.如果您需要/src/index.js 中的要求,那么您将需要:

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')

在这种情况下,您也无需指定实际文件,因为它默认为 index.js .但是,如果输入文件是 dabc.js 或其他名称,则还需要在该位置中指定该名称.

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.

这篇关于安装与安装将本地文件夹作为npm模块访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆