如何本身寫一個公用的NPM包

markdown-clear ,建立過程爲例,講解整個NPM包建立和發佈流程node

1 如何建立一個包

1.1 建立並使用一個工程

  • 在GitHub上新建一個倉庫,其名markdown-cleargit

  • clone 這個工程到本地es6

1.2 添加LICENCELICENSE文件, 說明對應的開源協議

MIT License
Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1.3 添加README或者ReadMe.md或者README.md文件

  • 說明項目的一些信息npm

  • 給出詳細參考資料的連接json

  • 給讀者一個總體的導航內容api

1.4 添加.gitignore 文件,忽略不須要提交的文件變動

1.5 初始化NPM包

  • 使用npm init 初始化工程

  • 按照提示填入相應的內容

1.6 到這裏的目錄結構

  • 工程三大件以及npm包配置文件都有了

markdown-clear
------------- .gitignore
------------- LICENCE
------------- README.md
------------- package.json

1.7 EditorConfig

跨編輯器的編輯器設置,網站掛了,EditorConfig

1.8 ESLint

新一代JavaScript代碼質量檢測工具ESLint

2 代碼結構組織

2.1 加入代碼相關的目錄

markdown-clear
-------------- src     // 源代碼目錄 好比coffee,typescript,es6+等代碼的目錄
-------------- lib     // 轉義生成的代碼目錄,好比babel轉義後的es5代碼的目錄
-------------- docs    // 代碼相關的設計和使用文檔
-------------- tests   // 相關的測試目錄

2.2 代碼實現

  • 寫代碼 src 目錄

  • 轉換後的代碼 lib 目錄

2.2.1 使用babel 轉換代碼
{
  "presets":["es2015","stage-0"]
}
  • 添加 npm 命令

"scripts": {
    "build": "babel src -d lib",
   }
2.2.2 實現一個能夠全局安裝的npm包
  • 添加package.json的配置

"bin": {
    "markdown-clear": "./lib/cli.js"
  }
  • cli.js文件第一行添加

#!/usr/bin/env node

2.3 測試

  • 寫測試用例 tests 目錄

  • 調用最終生成的 lib 下面的目錄

  • 能夠考慮使用測試框架 mocha, jasmine, karma...

2.3.1 安裝測試
  • 使用npm 安裝本地文件 做爲本地包

npm install path/to/markdown-clear
  • 使用npm 安裝本地文件 做爲全局包

npm install path/to/markdown-clear -g

2.4 文檔輸出

  • 寫文檔 docs 目錄

  • 寫代碼相關的設計和使用文檔,沒有天然能夠不用寫

  • 這裏的文檔應該在README.md 中會有入口。

3 發佈NPM包

npm adduser USERNAME
  • 若是沒有登陸

npm login
  • 登陸後發佈包,在工程目錄下執行

npm publish
相關文章
相關標籤/搜索