关于npm安装全局模块,require时报Error: Cannot find module 'XXX'的解决办法

下午使用npm安装“cheerio”。css

npm安装有两种模式:html

本地 # npm install cheerionode

全局 # npm install cheerio -glinux

若是想要全局安装,你首先要先设置个全局路径npm

我在"node的安装位置/lib/node_modules/"目录下新建了文件夹node_global专门用来存放新安装的全局包vim

# npm config set cache "node的安装位置/lib/node_modules/node_global"dom

# npm config set prefix "node的安装位置/lib/node_modules/node_global"测试

这个时候能够安装了ui

# npm install cheerio -gspa

安装好以后,赶忙打开node,试着require刚安装的全局包

var n = require(‘cheerio‘)
Error: Cannot find module ‘cheerio‘
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)

失败了!!!

网上查了一大堆博客,原来是忘了设置环境变量。

NODE_PATH

关键的地方来了:

NODE_PATH怎么写?

不要误觉得就是你的刚设置的全局目录,我那样填写了。彻底没用。

实际上你能够经过下面这个命令查看一下cheerio到底在哪里。而后NODE_PATH就设置哪里

#npm list -g

个人系统显示以下:

/usr/node-v6.10.0-linux-x64/lib/node_modules/node_global/lib
├─┬ cheerio@0.22.0
│ ├─┬ css-select@1.2.0
│ │ ├── boolbase@1.0.0
│ │ ├── css-what@2.1.0
│ │ ├── domutils@1.5.1
│ │ └── nth-check@1.0.1
│ ├─┬ dom-serializer@0.1.0
│ │ └── domelementtype@1.1.3
│ ├── entities@1.1.1
│ ├─┬ htmlparser2@3.9.2
│ │ ├── domelementtype@1.3.0
│ │ ├── domhandler@2.3.0
│ │ ├── inherits@2.0.3

我是这样配置的:

# vim /etc/profile

#添加下面两行

export NODE_HOME=/usr/node-v6.10.0-linux-x64/lib/node_modules/node_global
export NODE_PATH=$NODE_HOME:$NODE_HOME/lib/node_modules

保存退出

别忘了

# source /etc/profile 使其生效

再次测试require

[root@aliyun node-v6.10.0-linux-x64]#node
> var n = require(‘cheerio‘)

undefined
>

 

再也不报错了!

总结:

想要在js文件中经过require(‘模块名’)来使用全局安装的模块,必须配置系统环境变量,才可以使用。不然,执行时,会报错,意为:没有找到要使用的该模块。