DEMO

Github

With the source code, read this article carefully, you will understand the essence of packaging, sparrow is small, all the viscera.

Remember before

Code beyond business code is what I like to call value-added code.

What do you mean?

As a programmer, you should have some time on your own that you can “play” with, in addition to completing the tasks assigned by your boss.

When existing frameworks and libraries don’t meet our needs, we should try to build our own tools. It is what you achieve that makes others who you are.

Do people care about the specific business logic code you write? I think they’re more concerned about how your plugin is used and how convenient it is for them to complete their own business code.

More generally, they won’t remember you, but they will remember your Api and remember you.

It’s also important to note that all technology is for the business, otherwise it’s bullshit.

background

Since I joined the new company, I have been busy with business development. In the process, I have used many awesome tools written by the leader. To tell the truth, heartfelt admiration, is simply the liberation of productivity, in ancient times, is to be canonized god drop.

Here’s an example:

The leader spent some time researching an automatic form generator. Writing a form configuration page by hand, plus form validation, can take half a day or longer.

How about now? All forms, styles, and validation can be configured in code and can be done in 20 minutes.

From this, I realized a truth:

Instead of doing the same thing over and over again, do the same thing with your heart.

I’m sure you want to be the man he thinks you are, but living in your own world all day, you may not know how to do that at the moment. Here’s what I want to tell you:

A key factor in growth is from imitation.

That’s right. Try reading other people’s code to see how they implement it, or take a walk on Github. There are so many great projects, just copy them.

As long as you want to learn, you can learn, but is the way to achieve good or bad, these need to be improved later.

In view of this article is about to get off topic, no more to say, into the topic…

The body of the

1. Differences and relationships between components and plug-ins

The difference between
  • Components tend to be used more often than plug-ins
  • Components tend to be smaller in scope than plug-ins
contact
  • Plug-ins can encapsulate components that expose data to plug-ins

Here do not do too much elaboration, have interest can refer to Lao Bu big this part of the article, write very easy to understand.

2. Prerequisites for implementing plug-ins

basis

You need to have a clear understanding of some advanced knowledge and related content of VUE, such as

  • Vue. Extend the constructor
  • $mount Manually mounts the instance
  • Mixin mixin injection
  • Parent-child component parameter transmission, cross-level component parameter transmission
  • Understand Vue constructors and Prototype objects
  • Register an account on NPM website
  • Webpack packaging
  • .
skills

The following skill is today’s development of the realization of the time, visual very useful:

How will your plugin be used in development

What do you mean? Just follow my train of thought


Because I want to implement a global toast plugin

    this.$toast('That man')
    // todo
Copy the code

Light popup text does not work, there should be a variable that controls the popup direction

    this.$toast('That man', {position:'topCenter'
    })
Copy the code

The state of the global toast should be different, such as common success, error, warning, normal…

    / / success to success
    / / error error
    / / warning warning
    / / general info
    this.$toast('That man', {position:'topCenter'.type:'success'
    })
Copy the code

There should be a time variable to control how long it takes to automatically disappear toast

    this.$toast('That man', {position:'topCenter'.type:'success'.closeTime: 3 // Control toast after 3 seconds
    })
Copy the code

Is there a business scenario where we don’t automatically disappear toast

    this.$toast('That man', {position:'topCenter'.type:'success'.closeTime: 3 // Control toast after 3 seconds
        autoClose: false
    })
Copy the code

If I want to trigger some callback actions after the toast ends, such as refreshing the list page after successfully deleting the toast

    this.$toast('That man', {position:'topCenter'.type:'success'.closeTime: 3 // Control toast after 3 seconds
        autoClose: true, callback () { ... }})Copy the code

The contents of toast can be quite long, so there should be two variables controlling the toast width and height respectively

    this.$toast('That man', {position:'topCenter'.type:'success'.closeTime: 3 // Control toast after 3 seconds
        autoClose: true,
        callback () {
            ...
        },
        width:300.height:80
    })
Copy the code

At this point, the basics should be covered, and there are some built-in issues to consider

  1. Do I, as a user, care about all these configuration items? Or do they all need to be configured?
  2. According to different status (success/error/warning/info), must want to use different colors to distinguish, and use a different icon, what is the relationship between them?
What should be done with multiple configuration items? – Default

For example, the default type in my project is info. When I use it, if no type is passed in, the default type is INFO

Since most toast scenes are short-lived on the page, autoClose is set to true

Since most toast texts are short, my default toast length and width of 300 and 80 should be sufficient

.

All of the above default configurations can be passed in to override the default parameters when used

What is the relationship between the toast icon, color and title for different states?

Save a map configuration table locally, according to the type passed in, I can know exactly what icon, color, title should be

To sum up:

  • Plug-in parameters should be kept to a minimum and focused on user concerns
  • The implementation of a plug-in or component should be based on usage scenarios
  • Developing a component or plug-in should maintain the open and closed principles of software engineering
  • A good plug-in or component is not achieved overnight, often need to find problems in the later use process, to improve
  • A component or plug-in must be well documented, and not everyone who uses it is concerned with its internal implementation. They are more concerned with getting started quickly
implementation

As mentioned above, components can expose data to plug-ins

The component is static, just exposing some parameter props. Plugins that allow us to dynamically inject some custom parameters into them. The implementation is done in components.

So I wrote a static component that defines the related variables mentioned above via props

Let’s look at script first

Let’s take a look at the HTML

As you can see, the internal implementation is quite simple, just controlling the internal presentation details through external props

At this point, the static component is almost complete (CSS style code is not posted here).

Note:

  • When defining props, it is better to use object notation as a constraint
  • Variable names are best known by name
  • Binding of class names can take full advantage of arrays and object forms provided by VUE or with computed properties

How can static components be used as plug-ins?

Here no longer do too much elaboration, vUE packaging plug-ins commonly used methods mainly have the following four, if there is doubt, suggest reading vUE development plug-ins, of course, I think you should also need to understand the use of vue.extend, plug-ins can not be realized without it.

Take a look at the key part: this file is also the entry file for our post-WebPack build

The content of this document involves knowledge points, but also the development of a VUE plug-in the most core content. Every line of code in it is full of killing machines

At this point, the plug-in implementation part is basically complete.

3. How do I upload my plugin to NPM

In this case, there are many tutorials on the web, and I understand that you only need to understand the following lines of code

 // webpack.config.js
 
 module.exports = {
  entry: process.env.NODE_ENV === 'development' ? './src/main.js' : './src/index.js'.output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/'.filename: 'build.js'.libraryTarget: 'umd'},...// package.json
  {
  "name": "mbs-toast"."description": "a toast plugin base on Vue2"."version": "1.0.0"."author": "xxx <[email protected]>"."license": "MIT"."private": false."main": "dist/build.js"."scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot"."build": "cross-env NODE_ENV=production webpack --progress --hide-modules".Copy the code
  • The entry file configuration here means that the entry file is main.js for development and debugging purposes, and the entry file is index.js for packaging purposes
  • The webpack-simple template uses build.js by default. It is not recommended to change it without special requirements
  • LibraryTarget attribute may be relatively unfamiliar to everyone, because generally if you only use Webpack in the project do not need to pay attention to these two attributes, but if you are developing class libraries, plug-ins, then these two attributes are necessary to understand, not clear can refer to the ibraryTarget attribute in Webpack
  • The main field in the package.json file specifies the entry that the NPM package refers to (remember to add, and the file name should be the same as mentioned in the second point above).

In order to facilitate my daily development, I have added SCSS and ESLint. In this way, I don’t need to manually install each time. If you are interested, you can read the README. Customize your own scaffold template

With that background in mind, there are just a few steps you need to take to make everyone happy

Hopefully, you will now be able to pass the formal program

NPM install -s XXX installs your private packageCopy the code

Finally, register your plugin in your entry file

import toastPlugin from 'xxx'Vue. Use (toastPlugin) // The second parameter of Vue. Use can be configured globally to make some custom configurationsCopy the code

Here, it’s all settled

You can have fun with it in your code

this.$toast('The dust has settled', {
    callback () {
      console.log('hello world')},type: 'success',
    // position: 'topRight',
    autoClose: false
})
Copy the code

The last

Before I wrote this plugin, I saw a giant wrapped plugin on Github. If you are interested in it, you must go to see it. I believe that you who love learning will be full of harvest. At the same time in the development of the plug-in, some styles and animation, also made the corresponding reference.

The source code of the plugin has been uploaded to MBS-Toast for your reference. At the same time, the form generator mentioned above, I also tried to achieve their own again, interested can join together oh. All the plugins and components are currently collected on Github, and the documentation and README are being improved

The school of science graduates, writing is not good, do not spray ~

Code word is not easy, and line and cherish!