一、創(chuàng)建項目
$ mkdir test-NPM //新建test-NPM 文件夾
$ cd test-NPM //進入test-NPM 文件夾
$ npm init //#輸入包名,版本號,已經其他信息,使用默認直接按回車
結果
package name: (my-test-1)
version: (1.0.1)
git repository:
author: luoshushu
license: (ISC)
About to write to /Users/susonglin/Desktop/test-NPM/package.json:
{
"name": "my-test-1",
"version": "1.0.1",
"description": "測試",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "luoshushu",
"license": "ISC",
"dependencies": {},
"keywords": []
}
Is this ok? (yes) y
接下來依次填寫, 不想填寫也可以一路(回車)Enter。
name:
你的模塊名稱。(必填)version:
版本號。(只要修改項目版本號就必須修改,必填)description:
描述自己的模塊。main:
指定了程序的主入口文件,require('xxx') 就會加載這個文件。這個字段的默認值是模塊根目錄下面的 index.js。scripts:
命令行。author:
作者信息,可以之后編輯更詳細一些。license:
代碼授權許可。參考keywords:
關鍵字,可以通過npm搜索你填寫的關鍵詞找到你的模塊。git repository:
git倉庫地址
以上可以大膽填寫,過后可以修改,更多配置請看。
初始化完成,項目中多出了package.json 文件
{
"name": "my-test-1",
"version": "1.0.1",
"description": "測試",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "luoshushu",
"license": "ISC",
"dependencies": {},
"keywords": []
}
二、編寫代碼
1、新建index.js(測試)
2、新建README.md(說明)
3、如圖

三、發(fā)布模塊
1、需要NPM賬號,沒有就注冊
2、在終端登錄NPM
$ npm login
# 輸入登錄用戶名
# 輸入登錄密碼
# 輸入的郵箱
ps:輸入的用戶、密碼、郵箱是當時www.npmjs.com注冊的時候填的
3、發(fā)布
$ npm publish
//出現(xiàn)以下是發(fā)布成功了
+ my-test-1@1.0.1
4、我踩的坑
坑1:
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You do not have permission to publish "oh-my-lib". Are you logged in as the correct user? : oh-my-lib
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/susonglin/.npm/_logs/2017-12-04T10_37_31_216Z-debug.log
原因:
你沒有權限發(fā)布“oh-my-lib”。您是否登錄為正確的用戶?:oh-my-lib,模塊名稱同名了,換個模塊名就好。
解決:
"name": "oh-my-lib",
//換成
"name": "my-test-1",
坑2:
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You cannot publish over the previously published version 1.0.1. : my-test-1
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/susonglin/.npm/_logs/2017-12-04T10_12_14_606Z-debug.log
原因:
您不能在之前發(fā)布的1.0.1版本上發(fā)布。:my-test-1 ,也就是我已經發(fā)布過一次了。
解決:
修改版本號。把"version": "1.0.1",改成 "version": "1.0.2",
坑3:
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! no_perms Private mode enable, only admin can publish this module: my-test-1
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/susonglin/.npm/_logs/2017-12-04T10_18_32_973Z-debug.log
susonglindeMacBook-Pro:test-NPM susonglin$ npm publish
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! no_perms Private mode enable, only admin can publish this module: my-test-1
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/susonglin/.npm/_logs/2017-12-04T10_19_16_518Z-debug.log
原因:
因為之前我為了加快下載速度用了國內的淘寶地址,只要換回原來的地址,重新登陸、發(fā)布即可。
解決:
$ npm config delete registry
$ npm login
$ npm publish
ps: 加快下載速度方法:$ npm config set registry https://registry.npm.taobao.org/