一、 什么是npm
npm 为你和你的团队打开了连接整个 JavaScript 天才世界的一扇大门。
它是世界上最大的软件注册表,每星期大约有30亿次的下载量,包含超过600000个包(package)(即,代码模块)。
来自各大洲的开源软件开发者使用 npm 互相分享和借鉴。
包的结构使您能够轻松跟踪依赖项和版本。
一句话总结:npm就是一个包管理工具
npm 由三个独立的部分组成:
1、网站: 是开发者查找包(package)、设置参数以及管理 npm 使用体验的主要途径。
2、注册表(registry): 是一个巨大的数据库,保存了每个包(package)的信息。
3、命令行工具 (CLI): 通过命令行或终端运行。开发者通过 CLI 与 npm 打交道。
二、安装
从 Node.js 网站安装 npm;安装nodejs 时 npm会自动安装。
更新 npm : npm install npm@latest -g.
其他的功能及使用方法就不在这过多赘述啦,接下来回到主题:如何在npm上发自己的包
三、发布包
要想在npm上发布自己的npm包,首先要现在npm官方网站上注册一个账号
注册完成之后新建一个空项目,我用的是VueCLI创建的初始项目; 然后在src目录下加一个 packages 目录:
在packages/utils/index.js中写逻辑代码 例:
function debounce(fn, t) { let timerId // 发生了闭包:闭包就是 函数包裹函数 在里层函数调用外层函数的变量 // 会返回一个函数 return function() { // 函数会不断触发 // 清除已经触发的定时器 clearTimeout(timerId) timerId = setTimeout(() => { // 调用 i++ fn.call(this) // 修改this指向 指向事件源 定时器的this指向window 用箭头函数 this指向的是上一级作用域的 mouseMove() 这个定时器是处理事件函数 }, t) }}
然后再main.js中导入:
const { debounce} = require('./utils/index')module.exports = { debounce,}
好啦,基础代码到此告一段落,接下来配置一下package.json这个文件
{
"name": "xxxxxx",
"version": "0.0.1",
"private": false, // 私有配置
"author": "你的名字",
"main": "./dist/xxxxxx.common.js", //xxxxx 你的包名
"files": [
"dist/*",
"src/*",
"public/*",
"*.json",
"*.js"
],
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"build-bundle": "vue-cli-service build --target lib --name xxxxx ./src/packages/index.js" //xxxxx 你的包名
},
// ···
}
四、发布
首先要在终端登录刚刚注册的npm账号:
$ npm login
Username: (注册时的用户名)
Password: (密码不显示的)
Email: (this IS public) (注册时的邮箱)
Logged in as xxxxxx on http://registry.npmjs.org/.
发布命令:
npm publish
发布过程中出现的错误:
1、需要验证一下注册的邮箱
npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT http://registry.npmjs.org/xxxxxx - you must verify your email before publishing a new package: https://www.npmjs.com/email-edit
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.
2、 记得修改package.json中的 versions 版本号
npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT http://registry.npmjs.org/xxxxxxx - You cannot publish over the previously published versions: 0.0.2.
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.
3、非官方源,需要切换到官方源:registry.npmjs.org/
npm ERR! 403 Forbidden - PUT http://registry.npm.taobao.com/xxxxxxx - no_perms
切换命令:
NPM 全局配置切换到官方源 npm config set registry https://registry.npmjs.org
全局配置切换到淘宝源 npm config set registry https://registry.npm.taobao.org
4、切换源之后记得登录
npm ERR! 401 Unauthorized - PUT https://registry.npmjs.org/xxxxx - You must be logged in to publish packages.
登录:
npm login
5、包名重复:
npm ERR! 403 Forbidden - PUT https://registry.npmjs.org/xxxxx - You do not have permission to publish "xxxxx". Are you logged in as the correct user?
需要重命名你的package.json中的name。即使你在npm官网没有搜到你预设的包名,它可能也被发布占用过,需要修改你的包名。
五、更新
npm publish