将vue2组件发布成一个npm包

参照
https://juejin.cn/post/6867798692460494861
v将vue2组件发布成一个npm包_第1张图片
文件目录如上

1. npm init -y

2. src目录

index.js

import Toast from './toast.vue'

Toast.install = (Vue) => {
  Vue.prototype.$toast = (msg, duration) => {   //添加一个实例方法 这样全局的实例都可以调用$toast方法了 msg、duration是调用$toast时传入的两个参数
    if (!msg) {
      return;
    }
    duration = duration || 1500;  //如果不传toast持续时间则默认使用此时间
    const constroct = Vue.extend(Toast)  //构造器
    const instance = new constroct();   //创建实例
    instance.msg = msg || '';           //将$toast(msg,duration)中的msg传入组件的data中
    const tpl = instance.$mount().$el   //vue实例未挂载时可这样拿到它的dom 后续可对它的dom进行操作

    document.querySelector('body').appendChild(tpl);
    setTimeout(() => {
      document.querySelector('body').removeChild(tpl)
    }, duration);
  }
}

export default Toast;

toast.vue

<template>
  <div class="toast">{{msg}}</div>
</template>
<script>
export default {
  name: "Toast",
  data() {
    return {
      msg: ""
    };
  }
};
</script>
<style scoped>
.toast {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  width: fit-content;
  height: 44px;
  background-color: rgba(0, 0, 0);
  display: flex;
  justify-content: center;
  align-items: center;
  padding-left: 10px;
  padding-right: 10px;
  color: #fff;
  border-radius: 5px;
}
</style>

pakage.json

{
  "name": "/* toast-component11 */",
  "version": "3.0.9",
  "description": "",
  "main": "dist/toast.js",
  "scripts": {
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.11.5",
    "@babel/preset-env": "^7.11.5",
    "babel-loader": "^8.1.0",
    "css-loader": "^4.2.2",
    "style-loader": "^1.2.1",
    "vue-loader": "^15.9.3",
    "vue-template-compiler": "^2.6.12",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12"
  }
}

3.npm i

4. npm run build

5.npm pack(这一步主要是生成toast-component-1.0.0.tgz,为了在本地测试,可用可不用)

6. 发布包

先登录

设置源 npm config set registry https://registr.npmjs.org (如果是公司的源请自行更换)

npm login

npm adduser(这一步如果报错)

npm ERR! Unexpected token < in JSON at position 0 while parsing near ‘<!DOCTYPE HTML P
运行

// 顺序执行如下代码即可
npm config get proxy
npm config get https-proxy
npm config set registry https://registry.npmjs.org

正常之后输入你的npm的账号和密码

npm publish

项目中使用

yarn add toast-component11 
或者  npm install toast-component11  

main.js

import Toast from 'toast-component11'
Vue.use(Toast)

组件中使用

<template>
  <div class="hello">
    <div @click="showToast">点我出toast</div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
    }
  },
  methods: {
    showToast() {
      this.$toast('hello world', 2000)
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
</style>

你可能感兴趣的:(总结,#,Vue组件,npm,javascript,webpack)