npm包開發與發佈

 

把通用的功能開發成npm包,便用使用和維護,更重要的是能夠分享給廣大的開發者,是否是很激動人心!node

那麼,步驟以下:git

1.建立項目github

建立項目目錄,npm init ,根據須要輸入配置信息(建完後也能夠在package.json中自行修改)npm

建立完成後項目目錄下會有一個package.json文件json

配置項測試

name: 說明了npm包的名稱,也就是publish後能夠在npmjs中經過該名稱搜索到ui

version:版本號this

main:入口文件spa

 

2.建立index.js文件,內容以下:命令行

 1 function addZero(num) {
 2   return num > 9 ? num : '0' + num
 3 }
 4 
 5 let formatter = {
 6   date: null,
 7   init(date) {
 8     try {
 9       if (date) {
10         this.date = new Date(date)
11       }
12     } catch (error) {
13       console.info(error)
14     }
15   },
16   getDateTime () {
17     let date = this.date || new Date()
18     let res = ''
19     res = date.getFullYear() + '-' + addZero(date.getMonth() + 1) + '-' +addZero(date.getDate())
20     + ' ' + addZero(date.getHours()) + ':' + addZero(date.getMinutes()) + ':' + addZero(date.getSeconds())
21     return res
22   },
23   getDate () {
24     return this.getDateTime().split(' ')[0]
25   },
26   getTime () {
27     return this.getDateTime().split(' ')[1]
28   }
29 }
30 
31 module.exports = formatter
module.exports = formatter意思是把formatter輸出。

3.測試
建立test-formatter.js,導入index並使用其中的方法
1 let formatter = require('./index') // 導入
2 formatter.init('2018-6-9')
3 console.info(formatter.getDateTime())

命令行輸入 node test-formatter.js  執行,結果爲:

 

4.測試沒有問題,那麼須要建立一個ReadMe文件進行說明

主要包含:

介紹,安裝方法,github地址,使用示例

 1 # datetime-format-wsy
 2 格式化時間,獲取2019-08-07 15:06:32或2019-08-07或15:06:32
 3 
 4 # install
 5 npm install -g datetime-format-wsy
 6 
 7 #github
 8 https://github.com/shiyuan598/FrontEnd/tree/master/npm/datetime-format
 9 
10 #usage
11 let formatter = require('./index')
12 formatter.init('2018-6-9')
13 console.info(formatter.getDateTime())

此時項目的目錄結構以下:

 

5.下面就能夠發佈了

先要有一個npm帳號,,若是沒有請到 https://www.npmjs.com 註冊

命令行輸入:

npm login

根據提示依次輸入用戶名、密碼,登陸成功後會顯示用戶名。

命令行輸入:

npm publish

 完成發佈。

若是是由於使用了淘寶鏡像致使publish不成功,能夠按以下步驟操做:

npm i -g nrm

nrm use npm

再次npm publish

 

6.使用

發佈成功後就能夠在npmjs中搜索、也能夠安裝使用了。

在npmjs搜索的結果:

安裝:

命令行輸入:npm install datetime-format-wsy --s

 

安裝完成後項目目錄下會增長package-lock.json描述了該包的信息:

 1 {
 2   "name": "datetime-format-wsy2",
 3   "version": "1.0.1",
 4   "lockfileVersion": 1,
 5   "requires": true,
 6   "dependencies": {
 7     "datetime-format-wsy": {
 8       "version": "1.0.1",
 9       "resolved": "https://registry.npmjs.org/datetime-format-wsy/-/datetime-format-wsy-1.0.1.tgz",
10       "integrity": "sha512-klyoj8r2KbOqN9zngjplMr+EWU+cGqa1KgzNn+TUtEpzvYqmnJvj+P90gYXgm0sKVd4+30GLesocoRmMWh3Q0Q=="
11     }
12   }
13 }

 在test-format.js中使用

1 let timeFormat = require('datetime-format-wsy')
2 let date = timeFormat.getDateTime()
3 console.info(date)

結果:

(另外,使用node運行js文件,文件改動後不會自動更新,須要重複運行node命令,

能夠使用nodemon代替,自動重啓,提高效率,

安裝:npm install -g nodemon

使用: nodemon filename.js)

 

代碼github地址:

https://github.com/shiyuan598/FrontEnd/tree/master/npm/datetime-format
 

 僅介紹npm包開發與發佈的流程,若有問題請不吝賜教,歡迎留言交流~

相關文章
相關標籤/搜索