1. 程式人生 > 實用技巧 >npm包的上傳和使用,nrm的使用介紹

npm包的上傳和使用,nrm的使用介紹

假設公司當前有個npm私庫:http://npm.abc.cn

根據以下步驟進行分享:

  1. 介紹簡單包的製作,作為上傳前的檔案準備
  2. npm登入
  3. 釋出剛剛製作的包
  4. 在專案中引入釋出的包
  5. 刪除釋出的包
  6. nrm介紹及使用

一、簡單包的製作

①:新建一個資料夾

②:進入資料夾並初始化npm

成功後會生成一個package.json檔案

③:建立一個app.vue頁面和index.js

app.vue

 1 <template>
 2   <div class="">{{text}}</div>
 3 </template>
 4 
 5 
 6 <
script> 7 8 export default { 9 name: 'Test', 10 components: {}, 11 props: { 12 text: { 13 type: String, 14 default: '' 15 } 16 }, 17 data() { 18 return { 19 }; 20 }, 21 computed: {}, 22 watch: {}, 23 methods: {}, 24 created() {}, 25 mounted() {},
26 }; 27 </script> 28 <style lang='scss' scoped> 29 </style>

index.js

1 import text from './app.vue'
2 export default text

此例子是接收一個字串並暴露出來

至此,簡單的包製作完成。

二、npm登入

npm登入指令:npm login

登入公司私庫:npm login --registryhttp://npm.abc.cn

登陸成功。

注意:輸入密碼是沒有顯示的,閉著眼輸,對就對,錯就重新來。

三、釋出剛剛製作的包

釋出指令:npm publish

釋出到公司私庫:npm publish--registryhttp://npm.abc.cn

釋出一定要注意改版本號。

簡單說明一下版本號:版本號由3部分構成大版本號、小版本號和補丁修復版本號。

比方說:1.2.3中1是大版本號,除非很大改動,才會改這個版本號。2是小版本號,正常迭代會改動到此版本號,3是補丁修復和優化等,有小改動,都在此地方修改

版本號前面通常有2個常見的字元~和^,沒有的話表示固定版本

~會匹配最近的小版本依賴包,比如~1.2.3會匹配所有1.2.x版本,但是不包括1.3.0

^會匹配最新的大版本依賴包,比如^1.2.3會匹配所有1.x.x的包,包括1.3.0,但是不包括2.0.0

在引用包的時候,根據情況,可以進行適當使用字首。

如遇下面報錯,檢查一下登入是否正確檢查下映象代理,檢查下包名在npm官網是不是已經存在了

我們換個名字再次釋出

釋出成功,去npm看看

四、在專案中使用

①:安裝npm install wuzhiquan-npm-test --save(cnpm install wuzhiquan-npm-test --save)

安裝成功。

②:引入並呼叫

 1 <template>
 2   <div id="app">
 3     <test :text="'我叫吳之全'"/>
 4   </div>
 5 </template>
 6 
 7 
 8 <script>
 9 import test from 'wuzhiquan-npm-test'
10 
11 export default {
12   name: 'App',
13   components: {
14     test
15   }
16 }
17 </script>
18 
19 <style>
20 </style>

成功輸出

五、刪除釋出的包

刪除指令:npm unpublish wuzhiquan-npm-test--force

刪除公司私庫的包:npm unpublish wuzhiquan-npm-test--force--registryhttp://npm.abc.cn

刪除成功,去npm看看

六、nrm介紹及使用

nrm 是一個 npm源管理器,允許你快速地在 npm源間切換。當然,不使用nrm也能切換源:npm set registryhttps://registry.npm.taobao.org/,但是如果頻繁切來切去,增加操作的同時,地址難免也會不出錯。還是使用管理器更加方便

首先需要全域性安裝:npm install -g nrm(cnpm install -g nrm)

常見指令:

①:檢視可選源:nrm ls,帶*表示當前使用的源

②:檢視當前使用源:nrm current

③:切換源:npm user<registry>,<registry>為源名

④:新增源:nrm add<registry> <url>,<registry>為源名,<url>為地址

⑤:刪除源:nrm del<registry>,<registry>為源名

⑥:測試源響應時間、訪問速度:nrm test <registry>,<registry>為源名

經測試,taobao源比npm源要快