vue插件封装

构建一个webpack项目


image.png
image.png

如果是样式更改的需要用watch来监听props的参数改变样式

image.png
  // 1. 添加全局方法或属性
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }
 // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })
  // 3. 注入组件选项
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })
 // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}  

1、package.json文件
打包需要需要修改的配置文件

{
  "name": "example",
  "description": "测试",
  "version": "1.0.0",
  "author": "mangseng666 ",
// 配置main结点,方便在其它项目中使用import XX from '包名'来引用
  "main": "dist/example.js",
//开源协议
  "license": "MIT", 
//组件为公用包,所以private要设置为false
  "private": false,
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
  },'
//代码所在的仓库地址
 "repository": {
  "type": "git",
  "url": ""
  },
  "dependencies": {
    "vue": "^2.5.11"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ],
//指定关键词 可写可不写
 "keywords": [
  "example"
  ],
 // 项目官网的url
 "homepage": "https://github.com/echo-lu/mini-sliders/blob/master/README.md",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-stage-3": "^6.24.1",
    "cross-env": "^5.0.5",
    "css-loader": "^0.28.7",
    "file-loader": "^1.1.4",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "vue-loader": "^13.0.5",
    "vue-template-compiler": "^2.4.4",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.9.1"
  }
}

webpack.config.js

output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'example.js',
      //因为webpack的默认打包形式为
      //(function () {
      //  return 'hello world'
      //})()
    library:'example', 
    //添加library之后变为了 var example = (function () {
    //return 'hello world'
    //})()
    //在js文件里通过Require来导入使用的话就使用libraryTarget
    libraryTarget:'umd',
    umdNamedDefine:true,
  },

最后是index.html

image.png

npm build 打包

npm pack 压缩 会生成一个 ****.tgz文件

本地测试 npm install "tgz文件的地址"

在main.js里面
import 进来之后
Vue.use()

就可以像其它组件一样正常使用啦

image.png

你可能感兴趣的:(vue插件封装)