0 注册npm账户
全名:
邮箱:
用户名:发布scoped包时会用到
密码:
1 发布包
npm官方建议规范的包至少包含:
●package.json(包的基本信息)
●README.md(文档)
●index.js (入口文件)
1.1 创建项目
mkdir water-pkg && cd water-pkg
1.2 创建package.json
npm init 或者 npm init -y
按照提示一步步完善即可,也可使用 npm init -y 使用npm默认设置,稍后再通过编辑package.json修正。
注意:本次演示的包的入口文件是index.js,请务必确保package.json中字段main对应的值是index.js。
最终结果:
{ "name": "water-pkg", "version": "1.0.0", "description": "my first npm package", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "npm", "packge" ], "author": "water", "license": "ISC" }
1. 3 创建README.md
### water-pkg This is my first npm package!
1. 4 创建index.js
module.exports = { printMsg: function () { console.log('hello npm!'); } }
最终的目录结构:
└── water-pkg ├── README.md ├── index.js └── package.json
1. 5 发布
npm publish
可能报的错:
未登录
npm ERR! code ENEEDAUTH
npm ERR! need auth auth required for publishing
npm ERR! need auth You need to authorize this machine using npm adduser
解决办法:
npm adduser
输入:
●用户名
●密码
●邮箱
以上问题解决后再次执行发布命令npm publish,发布成功!
去npm 官网搜索便可以看自己发布的包了!👍👍👍
2 发布scoped包
2.1 创建项目
mkdir babel && cd babel
2.2 创建 package.json
npm init
最终结果:
{ "name": "babel", "version": "1.0.0", "description": "my scoped test package", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "npm", "package" ], "author": "yuyy", "license": "ISC" }
2.3 创建README.md && 创建index.js (此处省略…)
最终的目录结构:
└── babel ├── README.md ├── index.js └── package.json
2.4 发布
npm publish
报错:没有发布权限
npm ERR! publish Failed PUT 401
npm ERR! code E401
npm ERR! This package requires that publishers enable TFA and provide an OTP to publish. For more info, visit: https://go.npm.me/2fa-guide : babel
原因:已经存在babel包,而我又不是babel的发布者
2.5 加作用域
npm init --scope=@water -y
@符号后面的是你注册npm账户时的username,如果不记得可以通过npm whoami查询。
上面的命令其实是在重新生成package.json,只是会给包增加了作用域,执行完后package.json现在的内容:
{ "name": "@water/babel", "version": "1.0.0", "description": "my scoped test package", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "npm", "package" ], "author": "yuyy", "license": "ISC" }
2.6 公共发布
npm publish --access public
去npm 官网搜索便可以看自己发布的包了!👍👍👍 (此处的包是 @water/babel)