在 Vue 项目中,上传一个组件到 npm 官网

82 阅读1分钟

在 Vue 项目中,上传一个组件到 npm 官网

  1. 在 components 文件夹下有一个可以正常使用的组件
  2. 创建一个 js 文件,引入组件
import hxLayout from "@/components/Layout"//引入组件
const coms = [hxLayout]//将来如果有其它组件,都可以写到这个数组里//批量组件注册
const install = function(Vue) {
  coms.forEach(com => {
    Vue.component(com.name, com)
  })
}
​
export default install //这个方法以后再使用的时候可以被use调用
  1. 修改 package.json文件,增加一个 script,自定义打包
"scripts": {
    "ui": "vue-cli-service build --target lib ./src/ui/index.js --name ui-modal --dest dist-modal"
  }
  1. 打包生成ui-modal文件夹,进入该文件夹下,初始化一个新的 package.json
{
  "name": "hx-layout",
  "version": "1.0.1",
  "description": "前端 vue 组件化 layout",
  "main": "ui-modal.umd.min.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [
    "vue",
    "js",
    "layout"
  ],
  "author": "nianjun",
  "license": "ISC"
}
​
  1. 终端进入当前目录,切换到官方镜像源(npm config set registry https://registry.npmjs.org/
  2. 登录 npm
npm login
  1. 发布到官网
npm publish

进入官网的 packages 页面即可找到已发布的包(会有一些延迟,耐心等待)