封装组件发布到npm上
- 注册一个npm账号
在npm官网注册https://www.npmjs.com/
- 给代码库起名字
不可有重复包名,包名重复不能提交
- 创建项目
需要一个package.json文件,这个文件不仅仅是用来标明依赖和npm script脚本,也可以是一个npm包被外界识别的配置文件。
因为配置文件内容比较多,可以选择自己手写,或者npm init
package.json
{ "name": "xxx", "version": "1.0.1", "description": "公共功能的js", "main": "index.js",//你要发布到npm上的组件 "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "author": "xxx", "license": "ISC", "dependencies": { "core-js": "^3.6.5", "vue": "^2.6.11" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-service": "~4.5.0", "babel-eslint": "^10.1.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^6.2.2", "vue-template-compiler": "^2.6.11" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "eslint:recommended" ], "parserOptions": { "parser": "babel-eslint" }, "rules": {} }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] }
- 发布代码
先登录你的账号
$ npm adduser Username: your name Password: your password Email: yourmail
npm publish
如果提交成功
- 测试是否发布成功
- 到官网上查看有没有
- 下载下来
npm install 你发布的包名 --save
- 常见报错
下面是一些常见报错:
- npm publish failed put 500 unexpected status code 401
一般是没有登录,重新登录一下 npm login 即可
- npm ERR! you do not have permission to publish “your module name”. Are you logged in as the correct user?
包名被占用,改个包名即可。最好在官网查一下是否有包名被占用,之后再重命名
- you must verify your email before publishing a new package
邮箱未验证,去官网验证一下邮箱