極簡的 NodeJS npm 模塊開發

極簡的 NodeJS npm 模塊開發node

如何完成一個NPM模塊?動手實驗,照着弄,完了就懂了。
推薦下cmder 給windows的用戶替代cmd,有了它日子會幸福不少。npm

再來一個helloworld,反正世界上已經不少。

mkdir hellopack
cd hellopack
λ type con: >hello.js

exports.hello = function ( name ) {
    return  "Hello " + name ;
}
^Z

建立打包文件

λ type con: >package.json
{
        "name": "hello",
        "version": "0.0.1",
        "main": "hello.js"
}

^Z

測試安裝

cd ..
npm install packdemo/
λ ls node_modules\hello
hello.js package.json

說明:npm install 就是拷貝目錄到node_module 的一個目錄。固然package.json 作了些回味無窮的修改json

diff hellopack\package.json node_modules\hello\package.json

1,5c1,11
<  {
<     "name": "hello",
<     "version": "0.0.1",
<     "main": "hello.js"
<   }
\ No newline at end of file
---
> {
>   "name": "hello",
>   "version": "0.0.1",
>   "main": "hello.js",
>   "readme": "ERROR: No README data found!",
>   "_id": "hello@0.0.1",
>   "scripts": {},
>   "_shasum": "0d23e155b4a222c8f8496b9c01c9cb9403d1fe2c",
>   "_from": "packdemo",
>   "_resolved": "file:packdemo"
> }

注意: 目錄的名字就是package.json內的name,而不是你的開發目錄名。windows

而js文件則是照着拷貝:測試

diff node_modules\hello\hello.js packdemo\hello.js
(無輸出)

驗證包安裝。留意直接寫包名便可,不須要指定位置

λ node
> var a = require("hello")
undefined
> a
{ hello: [Function] }
> a.hello(1)
'Hello 1'

發佈到npm - 註冊賬號

λ npm adduser
Username: name 
Password:
Email: mail@gmail.com

發佈到npm - 發佈

cd hello
npm publish

發佈成功了嗎?

https://www.npmjs.com/search?q=helloui

有啊,還不少。3d

相關文章
相關標籤/搜索