vue 组件封装及npm发布

目录

  • 使用vue cli创建一个项目
  • 编写插件
  • 使用vue cli打包
  • 发布准备
    • 编写package.json
    • 登录npm账户
    • 作用域发布公有包
  • 注意事项
  • 参考资源

使用vue cli创建一个项目

在安装了vue cli的前提下,通过如下命令初始化一个项目

vue create hello-world

编写插件

编写vue插件,按照vue文档要求的规范,入口文件应该暴露一个包含install方法的对象

import preview from '../src/components/preview'

let pdfPreview = {}

pdfPreview.install = function(Vue){
  Vue.component(preview.name, preview)
}

export default pdfPreview

使用vue cli打包

使用下面命令进行打包

vue-cli-service build --target lib --name myLib [entry]

发布准备

编写package.json

下面是一个例子

{
  "name": "@lichunshan/pdf-preview",
  "version": "1.0.4",
  "private": false,
  "description": "pdfjs-dist based mobile pdf preview component",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "build:lib": "vue-cli-service build --target lib --name pdf-preview lib/index.js"
  },
  "author": "lichunshan",
  "main": "dist/pdf-preview.common.js",
  "files": [
    "dist/*",
    "src/*",
    "public/*",
    "*.json",
    "*.js"
  ],
  "dependencies": {
    "core-js": "^3.6.4",
    "pdfjs-dist": "^2.2.228",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.2.0",
    "@vue/cli-plugin-eslint": "^4.2.0",
    "@vue/cli-service": "^4.2.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.1.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"
  ],
  "keywords": [
    "vue",
    "component",
    "pdf",
    "pdfjs-dist"
  ],
  "license": "MIT",
  "homepage": "https://github.com/lichunshan/pdf-preview"
}

登录npm账户

运行 npm login输入用户名和密码

作用域发布公有包

运行 npm publish --access=public,因为作用域包一般都是私有的发布都是需求收费的,但是我们可以选择公开的发布方式,将access参数指定为public

注意事项

  • 每次构建都要修改package.json中的版本号,否则发布失败
  • 构建要选择lib模式,不要选择wc,后者无法通过Vue.use的方式使用插件,而只能在保证全局Vue可用的条件下引入文件使用

最后,附上本项目地址移动端vue pdf预览组件

参考资源

vue cli构建目标--库
vue官方文档,插件开发
如何使用创建、发布、使用作用域npm包
vue组件从开发到发布

猜你喜欢

转载自www.cnblogs.com/chunshan-blog/p/12486705.html