简体   繁体   English

我如何要求在全球范围内随npm安装的模块?

[英]How do I require modules installed with npm globally?

I have installed some-npm-module globally, but I get an error when I require() it: 我已经全局安装了some-npm-module ,但是当我require()它时出现错误:

$ node    
> const module = require('some-npm-module')
> import module from 'some-npm-module'

Error: Cannot find module 'some-npm-module'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at repl:1:12
    at realRunInThisContextScript (vm.js:22:35)
    at sigintHandlersWrap (vm.js:98:12)
    at ContextifyScript.Script.runInThisContext (vm.js:24:12)
    at REPLServer.defaultEval (repl.js:313:29)
    at bound (domain.js:280:14)

Core Node modules do seem to work without issue. 核心节点模块确实可以正常工作。 The following produces no errors: 以下不会产生任何错误:

const http = require('http');

Why does this happen? 为什么会这样? Am I installing the module correctly? 我是否正确安装模块?

Note that in this case I need to use the npm module in the terminal , not in a certain project. 请注意,在这种情况下,我需要在终端中而不是在某个项目中使用npm模块。

You should only install modules globally if you plan to call them on the command line, according to the documentation : 根据文档 ,仅当您计划在命令行上调用模块时,才应在全局安装模块:

If you want to use it as a command line tool, something like the grunt CLI, then you want to install it globally. 如果要将其用作命令行工具(如grunt CLI),则需要在全局安装它。 On the other hand, if you want to depend on the package from your own module using something like Node's require, then you want to install locally. 另一方面,如果您想使用Node的require之类的东西依赖您自己模块中的软件包,那么您想在本地安装。

This is because require() doesn't look in the global modules directory, so it'll never find some-npm-module if it's installed there. 这是因为require()不在全局模块目录中查找,因此,如果在该目录中安装了some-npm-module ,它将永远找不到。

Installing locally with npm install some-npm-module should resolve your issue and allow you to require from the REPL (as long as you consistently run the REPL from the same directory ). 使用npm install some-npm-module在本地npm install some-npm-module应该可以解决您的问题,并允许您向REPL提出要求(只要您从同一目录一致地运行REPL)。

Please Remove entire node_modules folder and re-install 请删除整个node_modules文件夹并重新安装

  • rm -rf node_modules rm -rf node_modules

  • npm install npm安装

After installing an npm module globally, to use it in your current project/dir, just link it. 全局安装npm模块后,要在当前项目/目录中使用它,只需链接它即可。

npm link module_name npm链接module_name

It should work. 它应该工作。

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

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