npm link 命令解析

c3tc3tc3t發表於2014-02-27

 文字轉的

對開發者而言,這算是最有價值的命令。假設我們開發了一個模組叫 test ,然後我們在 test-example 裡引用這個模組 ,每次 test 模組的變動我們都需要反映到 test-example 模組裡。不要擔心,有了 npm link 命令一切變的非常容易。

首先我們需要把 test 連結到全域性模式下:

cd ~/work/node/test # 進入test模組目錄
npm link # 建立連結到$PREFIX/lib/node_modules

那麼 test 的模組將被連結到 $PREFIX/lib/node_modules 下,就像我的機器上 $PREFIX 指到 /usr/local ,那麼 /usr/local/lib/node_modules/test 將會連結到 ~/work/node/test 下。執行指令碼 bin/test.js 被連結到 /usr/local/bin/test 上。

接下來我們需要把 test 引用到 test-example 專案中來:

cd ~/work/node/test-example # 進入test-example模組目錄
npm link test # 把全域性模式的模組連結到本地

npm link test 命令會去 $PREFIX/lib/node_modules 目錄下查詢名叫 test 的模組,找到這個模組後把 $PREFIX/lib/node_modules/test 的目錄連結到 ~/work/node/test-example/node_modules/test 這個目錄上來。

現在任何 test 模組上的改動都會直接對映到 test-example 上來。

 

再比如假設我們開發很多應用,每個應用都用到 Coffee-script :

npm install coffee-script -g # 全域性模式下安裝coffee-script
cd ~/work/node/test # 進入開發目錄
npm link coffee-script # 把全域性模式的coffee-script模組連結到本地的node_modules下
cd ../test-example # 進入另外的一個開發目錄
npm link coffee-script # 把全域性模式的coffee-script模組連結到本地
npm update coffee-script -g # 更新全域性模式的coffee-script,所有link過去的專案同時更新了。

 

 

 

原理  linux的系統下會自動執行ln -s 命令來建立一個軟連線指向你的全域性包路徑

 

這麼一定段文字有點繞。下面用畫圖解釋一下 

 

例:

test-example 使用需要 test模組,就是上文紅色文字

 

 

例2 :每個應用都用到 Coffee-script 上文藍色字

 

 

 

 

 

 

相關文章