twitter

Last time, we introduced how to build a React plugin. Today, we will discuss how to build a Vue plugin

The preparatory work

Since the react plugin uses the same structure as the last article, code testing, continuous integration, and NPM package distribution are all the same, so I won’t mention them here. Let’s start 😊

  1. Development dependency packages
{
    "devDependencies": {
        "@babel/core": "^ 7.0.0." "."@babel/preset-env": "^ 7.0.0." "."babel-loader": "^ 8.0.2." "."chai": "^ 4.2.0"."coveralls": "^ 3.0.2." "."css-loader": "^ 1.0.0"."jest": "^ 23.6.0"."style-loader": "^ 0.23.1"."vue": "^ 2.5.21"."vue-loader": "^ 15.5.0".// Parse the SFC file
        "vue-style-loader": "^ 4.1.2." "."vue-template-compiler": "^ 2.5.21".// Vue-loader synchronization dependency
        "webpack": "^ 4.17.2"."webpack-cli": "^ 3.1.0"}},Copy the code
  1. Webpack configuration
const path = require('path');
const { VueLoaderPlugin } = require("vue-loader");

module.exports = {
    mode: "production".// Production mode
    entry: { / / the entry
        "YanProgress": path.resolve(__dirname, './src/index.js')},output: { / / export
        path: path.resolve(__dirname, './dist'),
        filename: '[name].min.js'.publicPath: "./dist/".libraryTarget: 'umd'.// Pack in UMD mode
    },
    module: {
        rules: [{test: /\.vue$/.loader: 'vue-loader'.options: {
                    // During template compilation, the compiler can convert certain features to require calls
                    transformAssetUrls: {
                        video: ['src'.'poster'].source: 'src'.img: 'src'.image: 'xlink:href' // SVG}},// Only hit js files in SRC directory to speed up Webpack search
                include: path.resolve(__dirname, "./src"),}, {test: /\.js$/.use: [{loader: 'babel-loader'.options: {
                            presets: ['@babel/preset-env']}},],// Only hit js files in SRC directory to speed up Webpack search
                include: path.resolve(__dirname, "./src/"),}, {test: /\.css$/.loader: "style-loader! css-loader"}},plugins: [
        // Vue-loader ** This plugin is required! ** Its job is to copy and apply other rules you have defined to the corresponding language blocks in the.vue file.
        new VueLoaderPlugin
    ],
    resolve: { // If the file suffix is omitted, the following configuration is used by default
        extensions: ['.js'.'.vue'],},externals: { // Do not pack the vue
        vue: 'vue',}};Copy the code

Writing a plug-in

Writing a vue plugin is a bit more complicated 😢. According to the case on the official website, we need to provide an object containing the install method or a function (portal) that vue. use calls to register your plugin

  • Writing a
import Component from './YanProgress.vue'; // This is the SFC component you usually write

// Export an object containing the install method
let plugin = { // An install method is exported here
    install(Vue,options) { 
        // Write your code here, you can register components globally, you can also write global directives, you can also extend Vue methods
        // 1. Global components
        Vue.component('yan-progress',Component); 
        // 2. Global methods or attributes
        Vue.myGlobalMethod = function () {
            / / logic...
        }
        // 3. Global directives
        Vue.directive('my-directive', {
            bind (el, binding, vnode, oldVnode) {
                / / logic...}})// 4. Inject components
        Vue.mixin({
            created: function () {
                / / logic...}})// 5. Add instance methods
        Vue.prototype.$myMethod = function (methodOptions) {
            / / logic...}}};if (window && window.Vue) { // If you are doing incremental development (script introduces simple and crude development), you need to automatically register your plugin
    window.Vue.use(plugin);
}

export default plugin;

Copy the code
  • Write two
import Component from './YanProgress.vue'; // This is the SFC component you usually write

// Or we could write this as a function
function plugin(Vue,options) { 
        // Write your code here, you can register components globally, you can also write global directives, you can also extend Vue methods
        Vue.component('yan-progress',Component); }};if (window && window.Vue) { // If you are doing incremental development (script introduces simple and crude development), you need to automatically register your plugin
    window.Vue.use(plugin);
}

export default plugin;
Copy the code

The reason for this is that the source code below is available at 😄

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) { // We can pass both objects and functions
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > - 1) { // Avoid double registration of plug-ins
      return this
    }

    // additional parameters
    const args = toArray(arguments.1)
    args.unshift(this)
    if (typeof plugin.install === 'function') { // If it is an object with the install method
      plugin.install.apply(plugin, args) // Do not change the plugin's this (here this refers to the plugin object itself)
    } else if (typeof plugin === 'function') { // if it is a function
      plugin.apply(null, args) // Do not change the plugin's this (this should point to window, in browser non-strict mode)
    }
    installedPlugins.push(plugin)
    return this}}Copy the code

Open source contributions

Embrace open source, so that the community, and even the industry to develop more momentum, ah, deja vu of the foot, 😂

Note: For example, your star is the biggest encouragement to me and the motivation to support me to continue open source, 😄

  • Awesome – vue community awesome – vue
  • Other communities are availableGithubexplore

End scatter flower 🎉

👏 Welcome to join me again at Github 😊

  • Project address github.com/Yangfan2016…
  • Yangfan2016.github. IO
  • The react – yan – progress github.com/Yangfan2016…
  • Vue – yan – progress github.com/Yangfan2016…