How to build an Vue plug in and generate an npm package

  • 2021-09-11 19:13:29
  • OfStack

vue plug-in 1 is generally used to add global functions, which can be divided into:

Add a global method or property; Add global resources (instructions, filters, etc.); Add 1 component options through the global mixin method; Add Vue instance method on Vue. prototype; Create a library to provide your own API and provide one or more of the functions mentioned above;

1 Generally speaking, we prefer the fifth way in the project, by creating an js file containing a variety of global functions, instructions, filters, instance methods and so on that we need to add. It is not difficult to build such a plug-in, mainly using the install method provided by vue, passing in the Vue constructor and the parameter objects you can use; Add the corresponding function, export out, and introduce and register Vue. use () method where necessary; For specific use, refer to vue official website plug-in-development plug-in.

This time, I need to add 'Anti-crawling' function to my project. The specific implementation is that the back end returns the specified error code and the corresponding verification page after detecting that the user triggers the'anti-crawling 'rule, The front end monitors the error code in the global request, loads the verification page through the plug-in to let the user verify the error code, feeds back the verification result to the back end, and removes the verification page after the back end receives the verification result.

After the requirements are determined, we know that all the plug-in needs to do is create an vue component instance = > Load the page returned by the backend = > Parse and execute the js file = > Registers the global callback function that validates successfully. The specific operation is as follows:


const antiReptilian = {
 install(Vue, options) {
  Vue.$antirept = checkText => {
   if (!checkText) return;
   let wrapperTemp = Vue.extend({
    // 1 Create constructors, define templates 
    template:
     '<div id="antiReptWrapper" style="z-index:9999 !important;"></div>'
   });
   let antiObj = new wrapperTemp().$mount().$el; // 2 Creating an instance 
   antiObj.innerHTML = checkText;
   initScripts(antiObj);//3 Parsed and executed sequentially js
   let App = document.getElementById('app');
   let wrapper = document.getElementById('antiReptWrapper');
   if (wrapper) {
    return;
   }
   App.appendChild(antiObj); // 4 Add the created instance to the App Medium 
   window.checkSucceed = res => {
    // 5 Removing the instance after validation passes 
    App.removeChild(antiObj);
    window.location.reload();
   };
  };
 }
};

It should be noted that loading the verification page by setting innerHTML will cause the internal js file not to be executed; Therefore, we must also extract the js file of the verification page and reinsert it, and ensure the execution sequence of multiple internal js files. The specific code is as follows:


// Reintroduction js Documents 
const initScripts = function(cont) {
 let oldScripts = cont.getElementsByTagName('script');
 let newScripts = [];
 for (let i = 0; i < oldScripts.length; i++) {// Extract interior js Documents 
  let newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.innerHTML = oldScripts[i].innerHTML;
  if (oldScripts[i].src) {
   newScript.src = oldScripts[i].src;
  }
  newScripts.push(newScript);
 }
 while (oldScripts.length !== 0) {
  cont.removeChild(oldScripts[0]);// Remove the previous js Documents 
 }
 for (let i = 0; i < newScripts.length; i++) {
  if (i == 0) {
   cont.appendChild(newScripts[i]);
  } else {// Ensure that each js Files are executed in the previous order 
   newScripts[i - 1].onload = newScripts[
    i - 1
   ].onreadystatechange = function(event) {
    cont.appendChild(newScripts[i]);
   };
  }
 }
};

So far this simple plug-in functionality is complete, introducing, registering, and calling the Vue. $antirept () method where needed to pass in the page to be loaded;

The method of generating npm package from written plug-in is also simple, which is divided into the following steps:

1. Go to npm official website to register an npm account = > "npm official website";

2. Generate a simple npm package from the written plug-in:

Create an empty folder with the name of your npm package, and be careful not to duplicate the existing npm package; Cut to this folder, enter the command 'npm init' to generate an package. json file, and customize the internal information; Copy the written plug-in js file to the folder and rename it as index. js; Create an README. md file in the root directory, adding introductory information about the package (not required);

3. Publish the created package:

1. If the package is released for the first time, execute the command 'npm adduser' and enter the previously registered npm account number, password and email address;
2. If it is not the first time to publish the package, execute the 'npm login' command to log in, and also enter the npm account number, password and email address;
3. After logging in successfully, execute the command 'npm publish' in the folder just now, and then publish the npm package;
4. To update the previous package, you only need to change the version number and then execute the 'npm publish' command.

So far, a simple vue plug-in has generated an npm package. After using it, you don't need to load js files, and you can directly introduce it through npm. Other small partners can also have a happy play == > End of the play.

The above is how to build an Vue plug-in and generate npm package details, more information about vue to generate npm package please pay attention to other related articles on this site!


Related articles: