Node.js模塊是一種可以發(fā)布到npm的包。當(dāng)你創(chuàng)建一個(gè)新模塊的時(shí)候,你將從 `package.json` 文件開始。
使用 `npm init` 命令創(chuàng)建 `package.json` 文件。命令行中將會(huì)彈出package.json字段中要你輸入的值。兩個(gè)必填字段:名稱(name)和版本(version)。你可能也需要輸入主文件字段(main),可以使用默認(rèn)值 `index.js`。
如果你想為作者(author)字段添加信息,你可以使用以下格式(郵箱、網(wǎng)站都是選填的):
~~~
Your Name <email@example.com> (http://example.com)
~~~
一旦`package.json`文件創(chuàng)建好了,你將想要?jiǎng)?chuàng)建模塊的入口文件,如果使用默認(rèn)值,他將會(huì)是 `index.js`。
在此文件中,添加一個(gè)函數(shù),作為 `exports` 對(duì)象的一個(gè)屬性。這樣,require此文件之后,這個(gè)函數(shù)在其他代碼中就可以使用了。
~~~
exports.printMsg = function() {
console.log("This is a message from the demo package");
}
~~~
測(cè)試:
1. 將你的包發(fā)布到npm
2. 在你的項(xiàng)目外新建一個(gè)目錄,然后 `cd` 過去
3. 運(yùn)行 `npm install <package>`
4. 創(chuàng)建一個(gè)test.js文件,require這個(gè)包,并調(diào)用此方法(函數(shù))
5. 運(yùn)行 node test.js。終端將會(huì)輸出:This is a message from the demo package
恭喜你,你的第一個(gè)npm包創(chuàng)建成功了。
