Recently, I was doing a functional reconstruction, which was quite complicated, and there were multiple modules nested among each other, so I wanted to use mixin mode to “smooth out”, but I thought it was more conducive to expansion to make it a plug-in system, so I kept thinking about the differences between the two, and gradually blurred the boundary between the two.

Just look at Vue3 source code, see its plug-in concept and implementation, suddenly enlightened, finally understand the form and use of plug-in.

A plug-in is a complete module that has access to the runtime and is used to extend the host’s capabilities or to implement new functions with the help of the host’s capabilities. Plug-ins usually have access to the complete host object, so they can use all of the host’s capabilities.

I don’t know what you want to do, but I’ll give you everything I’ve got, okay

Therefore, the plugin needs to provide at least one hook function to be called by the host. The first argument to this function is usually the host object. Assuming the hook is called Install (), a simple plugin would look like this:

const Plugin = {
    install(Host, options) {
        // Extend host functionality
        Host.prototype.pluginMethod = function () {}
        
        // Call the host function
        Host.someMethod()
    }
}
Copy the code

The host needs to have a use() method to install the plug-in:

const Host {
    use(plugin, options) {
        plugin.install(Host, options)
    }
}

Host.use(Plugin)
Copy the code

In this design, the coupling between the host and the plug-in is very small, and the plug-in has very flexible functionality.

This is the basic idea of the plug-in, but there are three more things to consider when implementing it:

  1. Because only one hook function is required, the simplest plug-in can be a function;
  2. Functionally and semantically, plug-ins should have at least oneinstall()uninstall()Two methods;
  3. The issue of whether the host passes a class or an instance to the plug-in.

For 3, it can be seen that Vue2 transmits a class, while Vue3 transmits an instance. Both have their advantages and disadvantages. Generally speaking, static function transmits a class and dynamic function transmits an instance.

Once these concepts are understood, it is easy to design a plug-in system. Of course, there are more details to deal with when coding: plug-in conflicts, duplicate installations, host sandboxes, etc., but these should be determined by your specific requirements, and it is not recommended to get bogged down in these details at the beginning.

The idea behind feature refactoring is to build a core MVP first and then scale the functionality laterally. At that time, I always thought that plug-ins needed to have a life cycle, otherwise they were not very different from mixins. Now I realize that the life cycle has nothing to do with plug-ins. A plug-in is a fully functional host-dependent module, unlike a mixin.