2017年4月24日 星期一

建立和發布開源的npm模組


由於最近打算建立一些開源的項目來分享及交流一下,所以在這篇blog文裡,我做一做筆記,分享一下我是如何建立npm的模組,並且利用github分享出來。


參考文章:
npm官方的文件 - https://docs.npmjs.com/getting-started/publishing-npm-packages


這篇文章的Github:  https://github.com/crongjie/npm-rjn-helloworld




1. 首先,需要到以下網址,建立一個npm的賬號:
https://www.npmjs.com/signup


如果,沒有github賬號的話,也請到github裡面開一個帳號。
網址: https://github.com/join?source=header-home


2. 然後,到github給你的開源項目,建立一個新的項目:




這篇文章則建立一個名為"npm-rjn-helloworld"的開源項目作例子。

例子:
Github Repository名:  npm-rjn-helloworld
NPM 項目名: rjn-helloworld



3. 在Github建立完Repository以後,把新建立的Repository clone到你的電腦裡面。

4. 在git clone後的電腦文件夾裡面,輸入以下指令

npm init

5. 在裡面輸入你的項目內容和github內容。 以我的"rjn-helloworld"作例子,內容如下:





輸出的package.json如下:

{
  "name": "rjn-helloworld",
  "version": "1.0.0",
  "description": "a sample npm Hello world package",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/crongjie/npm-rjn-helloworld.git"
  },
  "keywords": [
    "helloWorld"
  ],
  "author": "RJ  (http://rj-memo.weebly.com/)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/crongjie/npm-rjn-helloworld/issues"
  },
  "homepage": "https://github.com/crongjie/npm-rjn-helloworld#readme"
}


6. 建立index.js (或者按你npm init時的entry point設定,在適當的位置,建立你的javascript文件)

這篇文章則以hello world作例子,內容如下:

module.exports.helloWorld = function() {
    return "hello world!";
}


7. 完成你的開源模組後,輸入以下指令,把你在npm新開的帳號加入到npm裡面。

npm adduser

8. 最後,輸入以下指令,把你的模組發布到npm上:

npm publish

畫面如下:

9.在發布後,網址則為:
https://www.npmjs.com/package/rjn-helloworld

在項目上, 導入剛才所發布的開源npm模組



1.輸入以下指令,把你的模組安裝到你的項目上:
以"rjn-helloworld"作例子:
npm install --save rjn-helloworld

2.在你的項目上,輸入以下代碼,使用你開源出來的模組:
以一個ES6的項目作例子:
import { helloWorld } from 'rjn-helloworld'

window.onload = function(e){ 
    console.log(helloWorld()); 
}

沒有留言:

張貼留言