我如何要求在全局范围内使用 npm 安装模块?

How do I require modules installed with npm globally?

我已经全局安装了 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)

核心节点模块似乎可以正常工作。以下不会产生错误:

const http = require('http');

为什么会这样?我是否正确安装了模块?

请注意,在这种情况下,我需要在终端中使用npm模块,而不是在某个项目中。

请删除整个 node_modules 文件夹并重新安装

  • rm -rf node_modules

  • npm install

如果您打算在命令行上调用它们,您应该只全局安装模块,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. 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.

这是因为 require() 不在全局模块目录中查找,所以如果 some-npm-module 安装在那里,它永远找不到。

使用 npm install some-npm-module 在本地安装应该可以解决您的问题并允许您从 REPL 请求(只要您始终 运行 来自 相同目录的 REPL ).

全局安装 npm 模块后,要在当前 project/dir 中使用它,只需 link 它即可。

npm link module_name

应该可以。