npm 发布自己组件包

npm 发布自己组件包

发布到 npm 上

  • 首先创建自己的npm账号
npm init
npm install
npm uninstall
npm config edit // 编辑
npm config ls -l // 查看 .npmrc 配置文件
npm config get cache // 查看 npm 缓存目录
npm config get prefix // 查看通过 npm install -g 和 cnpm install -g 或者yarn global add 安装包的基础路径, lib/node_modules
npm root -g // 查看全局安装包路径
npm get registry // 查看本地源地址
  • 初始化普通项目项目
npm init

// 包名 不能使用大写字母、驼峰命名法
package name: vue-message-box
// 版本
version:
// 介绍
description:
// 入口
entry point
// 项目启动的时候要用什么命令来执行脚本文件(默认为node app.js)
test command
//
git repository
// 
keywords
// 
author
// 
license:(ISC)

按照默认选项,我们初始化项目已经做好额,生成的 package.json 内容如下

{
  "name": "vue-message-box",
  "version": "1.0.0",
  "description": "基于Vue的一个弹出窗",
  "main": "index.js",
  "scripts": {
    "test": "npm start"
  },
  "author": "yingzi",
  "license": "ISC"
}

完整 package.json

{
  "name": "Hello World",  //name属性就是你的模块名称
  "version": "0.0.1", //version必须可以被npm依赖的一个node-semver模块解析
  "author": "张三",  //"author"是一个码农
  "description": "第一个node.js程序", //一个描述,方便别人了解你的模块作用,搜索的时候也有用。
  "mian":"index.js", //main属性指定了程序的主入口文件.
  "keywords":["node.js","javascript"],  //一个字符串数组,方便别人搜索到本模块
  "repository": { //指定一个代码存放地址,对想要为你的项目贡献代码的人有帮助。
    "type": "git",
    "url": "https://path/to/url"
  },
  "license":"MIT", //你应该为你的模块制定一个协议,让用户知道他们有何权限来使用你的模块,以及使用该模块有哪些限制,如BSD-3-Clause 或 MIT之类的协议
  "engines": {"node": "0.10.x"},
  "bugs":{ //填写一个bug提交地址或者一个邮箱,被你的模块坑到的人可以通过这里吐槽
    "url":"https://github.com/luoshushu",
    "email":"bug@example.com"
    }, 
  "contributors":[{"name":"李四","email":"lisi@example.com"}], // "contributors"是一个码农数组。
  "scripts": { //指定了运行脚本命令的npm命令行缩写。比如:输入npm run start时,所要执行的命令是node index.js。
    "start": "node index.js"
  },
  "dependencies": { //指定了项目运行所依赖的模块
    "express": "latest",
    "mongoose": "~3.8.3",
    "handlebars-runtime": "~1.0.12",
    "express3-handlebars": "~0.5.0",
    "MD5": "~1.2.0"
  },
  "devDependencies": { //指定项目开发所需要的模块
    "bower": "~1.2.8",
    "grunt": "~0.4.1",
    "grunt-contrib-concat": "~0.3.0",
    "grunt-contrib-jshint": "~0.7.2",
    "grunt-contrib-uglify": "~0.2.7",
    "grunt-contrib-clean": "~0.5.0",
    "browserify": "2.36.1",
    "grunt-browserify": "~1.3.0",
  }
}

-package.json 详细介绍: http://caibaojian.com/npm/files/package.json.html

  • 登陆 npm
npm login
按照提示 输入 用户名密码即可

登陆是可能出现错误

npm ERR! code E409
npm ERR! 409 Conflict - PUT https://registry.npm.taobao.org/-/user/org.couchdb.user:wangjiaxin - [conflict] User wangjiaxin already exists

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wangjiaxin/.npm/_logs/2021-12-13T07_24_53_438Z-debug.log

解决办法

npm login --registry https://registry.npmjs.org

或者修改 .npmrc 文件

registry=https://registry.npm.taobao.org/ 替换成 registry=https://registry.npmjs.org
426 Upgrade Required - PUT http://registry.npmjs.org/-/user/org.couchdb.user:wangjiaxin

解决办法

npm login --registry https://registry.npmjs.org

登陆成功

Logged in as wangjiaxin on https://registry.npmjs.org/.

发布包

npm publish --registry https://registry.npmjs.org

可能遇见问题

npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/vue-message-box - Package name too similar to existing package vue-messagebox; try renaming your package to '@wangjiaxin/vue-message-box' and publishing with 'npm publish --access=public' instead
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, or
npm ERR! 403 on a server you do not have access to.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wangjiaxin/.npm/_logs/2021-12-13T07_33_48_520Z-debug.log
// 包名 vue-messagebox 和我们要发布的vue-message-box 包名太相似, 并改为用 npm publish --access=public 命令发布

问题二

npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/vue-wjxlayout-box - Forbidden
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, or
npm ERR! 403 on a server you do not have access to.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wangjiaxin/.npm/_logs/2021-12-13T07_45_11_809Z-debug.log

原因是第一次注册npm账号,绑定邮箱没有验证,不允许发布包,到邮箱里验证一下即可

最后成功发布

问题三、重新登陆登陆授权即可

 You need to authorize this machine using `npm adduser`

问题四、可能是包名重复,更新包名

You do not have permission to publish "npm-vue-components". Are you logged in as the correct user

Twilio Authy 做验证使用

成功发布显示内容

npm notice 
npm notice 📦  vue-wjxlayout-box@1.0.0
npm notice === Tarball Contents === 
npm notice 274B .idea/modules.xml    
npm notice 458B .idea/npm-package.iml
npm notice 163B index.js             
npm notice 79B  npmrc                
npm notice 212B package.json         
npm notice === Tarball Details === 
npm notice name:          vue-wjxlayout-box                       
npm notice version:       1.0.0                                   
npm notice filename:      vue-wjxlayout-box-1.0.0.tgz             
npm notice package size:  782 B                                   
npm notice unpacked size: 1.2 kB                                  
npm notice shasum:        90feeedb143421ef4cef7733d39d1156e82c6079
npm notice integrity:     sha512-xz69oRusl60Kq[...]5X7TdaEY27VZQ==
npm notice total files:   5                                       
npm notice 
+ vue-wjxlayout-box@1.0.0

删除 已发布包

npm unpublish --registry=https://registry.npmjs.org vue-wjxlayout-box@1.0.0

// 删除成功
- vue-wjxlayout-box@1.0.0

编辑一个vue组件发布到npm,并在项目中使用

  • 使用 vue-cli 创建一个项目
vue create yingzi-npm-conponment
  • 新增目录 package,修改src 目录为 examples,在package 目录下新建index.js 内容如下
// 安装导出组件
import UseMessageBox from "./message-box/index.js";
import UIButton from "./button";

// 存储组件列表
const components = [
  UseMessageBox,
  UIButton
];

const install = function(Vue) {
  // 遍历注册全局组件
  components.forEach(component => {
    Vue.component(component.name, component);
  });

  Vue.prototype.$UseMessageBox = UseMessageBox;

};

/* istanbul ignore if  判断是否是直接引入文件 */
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}
// 导出的对象必须具有 install , can能被 Vue.use() 方法安装
export default {
  install,
  UseMessageBox,
  UIButton
};

  • 新建 组件 UIButton 和 UseMessageBox
// 新建button 文件夹 下面新建 button.vue 和 index.js
// /src/button.vue
<template>
  <div>
    <slot>
      我是组件按钮
    </slot>
  </div>
</template>
<script>
export default {
  name: "UIButton",
}
</script>

// index.js
import UIButton from './button'

UIButton.install = function (Vue) {
  Vue.component(UIButton.name, UIButton);
}

export default UIButton;

// 新建message-box文件夹 下新建 文件 index.js main.vue main.js
// /src/main.vue
<template>
	<transition name="el-fade-in-linear">
		<div class="message_box_layout" v-if="showClose">
			<div class="message_box_content">
				<slot name="title">
					<div class="message_box_title">
						<div class="message_box_title_content">
							<span>{{ title }}</span>
						</div>
					</div>
				</slot>
				<slot name="section">
					<div class="message_box_section">
						{{ message }}
					</div>
				</slot>
				<slot name="footer">
					<div class="message_box_footer">
						<button style="width: 125px" v-if="isShowCancel" @click="cancel"
							>取消</button
						>
						<button
							style="width: 125px; border: 0"
							:style="{ backgroundColor: confirmBackgroundColor }"
							@click="submit"
							>确定</button
						>
					</div>
				</slot>
			</div>
		</div>
	</transition>
</template>
<script>
export default {
	props: {
    isShowClose: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isShowClose (v, o) {
      console.log(v, o)
    }
  },
	data() {
    return {
      confirmBackgroundColor: "",
      showClose: "",
      options: "",
      isShowCancel: "",
      title: "提示",
      message: "提示内容"
    };
  },
  created() {
    console.log(this.props, this.isShowClose)
    this.showClose = this.isShowClose;
  },
  methods: {
		showMessageBox (option) {
			this.options = option || undefined;
			this.title = option.title || '提示';
			this.message = option.message;
			this.isShowCancel = !!option.isShowCancel;
			this.showClose = true;
			this.confirmBackgroundColor = option.confirmBackgroundColor || '';
		},
		cancel(){
			if (this.options.cancel) {
				this.options.cancel();
			}
			this.showClose = false;
		},
		submit(){
			if (this.options.submit) {
				this.options.submit();
			}
			this.showClose = false;
		},
	},
};
</script>

<style scoped>
.message_box_layout {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0,0,0, .7);
  z-index: 9999;
}
.message_box_content {
  width: 478px;
  height: 240px;
  background: #FFFFFF;
  border-radius: 2px;
  margin: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -100%);
}
.message_box_title {
  width: 100%;
  height: 52px;
  background: #FAFAFA;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 32px;
  padding-right: 21px;
  box-sizing: border-box;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);

}
.message_box_title_content {
  display: flex;
  align-items: center;
}
span{
  margin-left: 8px;
  font-weight: 600;
}
.message_box_section {
  width: 100%;
  height: 129px;
  padding: 48px 63px 0;
  box-sizing: border-box;
  font-size: 16px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
}
.message_box_footer {
  display: flex;
  justify-content: center;
}

button {
  width: 125px;
  height: 32px;
  border: 1px solid rgba(24,144,255,.8);
  background: rgba(24,144,255,.8);
  color: #FFFFFF;
  cursor: pointer;
}
button:active {
  background: rgba(24,144,255,.4);
}
</style>

// /src/mian.js
import Vue from "vue";
import UseMessageBoxComponent from "./main.vue";
// import merge from "./mergepro"
const MessageBoxConstructor = Vue.extend(UseMessageBoxComponent);

let instance;
const initInstance = () => {
    instance = new MessageBoxConstructor({
        el: document.createElement('div')
    })
    instance.$mount();
    ['modal', 'showClose', 'isShowClose'].forEach(prop => {
      console.log('----- showClise -----', prop)
      if (instance[prop] === undefined) {
        instance[prop] = false;
      }
    });
    console.log(instance)
    document.body.appendChild(instance.$el);
}

const UseMessageBox = function () {
    if (!instance) {
        initInstance();
    }
}

UseMessageBox.success = (option) => {
    UseMessageBox();
    instance.showMessageBox(option);
}

export default UseMessageBox;
export { UseMessageBox }

// 新建index.js
import UseMessageBox from "./src/main.js";

// UseMessageBox.install = function (Vue) {
//   Vue.component(UseMessageBox.name, UseMessageBox);
// };

export default UseMessageBox;

配置vue.config.js


module.exports = {
  pages: {
    index: {
      entry: 'examples/main.js',
      template: 'public/index.html',
      filename: 'index.html'
    }
  },
  chainWebpack: config => {
    config.module
      .rule('js')
      .include
      .add('/packages')
      .end()
      .use('babel')
      .loader('babel-loader')
  }
}

package.json 下添加新的script,添加main配置

"main": "dist/myLib.common.js",
"script": {
  "lib": "vue-cli-service build --target lib --name myLib packages/index.js"
}

// description 组件库的描述文本
// keywords 组件库的关键词
// license 许可协议
// repository 组件库关联的git仓库地址
// homepage 组件库展示的首页地址
// main 组件库的主入口地址(在使用组件时引入的地址)
// private 声明组件库的私有性,如果要发布到npm公网上,需删除该属性或者设置为false
// publishConfig 用来设置npm发布的地址,这个配置作为团队内部的npm服务器来说非常关键,可以设置为私有的npm仓库

运行 npm run lib 生成组件包发布到 npm

安装使用

import YingZi from "yingzi-vue-components"
import 'yingzi-vue-components/dist/myLib.css';
Vue.use(YingZi)

补充npm发包文件白名单

//当执行npm publish命令,默认包含的文件(不区分大小写)有

package.json
README (and its variants)
CHANGELOG (and its variants)
LICENSE / LICENCE
package.json属性main指向的文件
默认忽略的有

.git
CVS
.svn
.hg
.lock-wscript
.wafpickle-N
.*.swp
.DS_Store
._*
npm-debug.log
.npmrc
node_modules
config.gypi
*.orig
package-lock.json (use shrinkwrap instead)
// 想设置发布文件的黑名单,通过.gitignore或.npmignore这两个文件来设置忽略的文件或文件夹。
// 果你在项目中增加了 .npmignore,那么其会完全替代掉 .gitignore 的作用。
// 想设置发布文件的白名单,设置package.json中的files属性。
// 例如

files:["package.json","src"]
// 这里的优先级是files>.npmignore>.gitignore

npm 常用命令

npm -v   //查看版本号

npm --help   //查看npm所有命令

npm adduser  //添加 npm 账号,也可以去npm官网注册

npm init  //构建项目说明,生成 package.json文件

npm view jquery versions //查看历史版本信息(最多只能显示100条)

npm view node versions --json //查看所有版本信息

npm view jquery version  //查看最新版本信息

npm info jquery  //查看所有版本及jquery的信息

npm ls jquery //查看本地安裝的jquery版本

npm ls jquery -g //查看全局安裝的jquery版本

npm i jquery@3.2.3 //安裝指定版本

npm i jquery //安装推荐的版本

npm i jquery@latest //安裝指定、最新版本

npm install gulp 简写 npm i gulp //安装依赖

npm install gulp -S -D

npm install gulp@3.0.0 --save

npm update gulp //可以把当前目录下node_modules子目录里边的对应模块更新至最新版本 

npm update gulp -g  //可以把全局安装的对应命令行程序更新至最新版

npm uninstall gulp@3.0.0 --save //卸载依赖

npm install cnpm -g --registry=https://registry.npm.taobao.org  //安装淘宝镜像

npm config list  //查看npm的配置

npm config set registry https://registry.npm.taobao.org  //设置淘宝镜像源

npm config set registry https://registry.npmjs.org //设置npm源

npm set disturl  https://npm.taobao.org/dist //设置资源库从淘宝库获取

npm cache clean --force //清空npm本地缓存 ,用于对付使用相同版本号发布新版本代码的人

npm run dev / test / build  //执行script命令

npm login //发布包时登录npm账号用的

npm  publish   //发布包到npm官方库

npm unpublish   test   //撤销已发布的包

npm  unpublish  test  --force  //强制撤销

npm  unpublish   test@1.0.2  //可以撤销发布自己发布过的某个版本代码

搭建私有npm

  • 通过docker verdaccio 搭建

添加成员

npm set registry http://npm.xxxx.com
npm adduser --registry http://npm.xxxx.com
username:xxxx
password:xxxx
email: xxxx

自己搭建服务器发布包时存在上传文件件限制

  • 发布 报错 413 Request Entity Too Large
http {
  client_max_body_size 100m;
}
posted @ 2022-02-21 11:00  影的记忆  阅读(720)  评论(0编辑  收藏  举报