Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build a Vue CLI plug-in

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to build Vue CLI plug-ins, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.

Preface

If you are using the Vue framework, you probably already know what Vue CLI is. It is a complete system for rapid development of Vue.js, providing project scaffolding.

An important part of CLI is cli-plugins. They can modify the internal webpack configuration and inject commands into the vue-cli service.

A good example is @ vuecli-plugin-typescript: when you call it, it adds a tsconfig.json to your project and changes the type of App.vue, so you don't have to do it manually.

Plug-ins are very useful, but what if you want to have a plug-in for some specific library and it doesn't exist? Well, when we are in this situation. We decided to build it ourselves.

In this article, we will create a vue-cli-plugin-tiantian. It allows us to add the vue-rx library to our project and get RxJS support in our Vue application.

Let's take a look at the whole process.

Vue-CLI plug-in structure

First of all, what is the CLI plug-in? It is just a npm package with a certain structure. With regard to documentation, it must have a service plug-in as its main exit and can have additional features, such as generators and prompt files.

At present, it is absolutely not clear what a service plug-in or generator is, but don't worry-- it will be explained later!

Of course, like any npm package, the CLI plug-in must have package.json in its root folder and, preferably, a README.md with some instructions.

So let's start with the following structure.

. ├── README.md ├── index.js # service plugin └── package.json

Now let's take a look at the optional parts. The generator can inject additional dependencies or fields into the package.json and add files to the project. Do we need it?

Of course, we want to have rxjs and vue-rx as our dependencies. More specifically, we want to create some sample components if the user wants to add it when installing the plug-in.

Therefore, we need to add generator.js or generatorindex.js. I prefer the second way. The current structure looks like this:

. ├── README.md ├── index.js # service plugin ├── generator │ └── index.js # generator └── package.json

One more thing to add is a prompt file. I hope my plug-in will be able to ask users if they want to have a sample component. We will need a prompts.js file in the root directory to implement this behavior. So, the current structure is as follows:

Service plug-in (Service plugin)

A service plug-in should output a function that takes two parameters: an PluginAPI instance and an object that contains project local options.

It can modify the internal webpack configuration for different environment extensions and inject additional commands into vue-cli-service.

Let's think about this: do we want to change the webpack configuration or create an additional npm task in some way?

The answer is no, we just want to add some dependencies and sample components if necessary. Therefore, what we need to change in index.js is:

Module.exports = (api, opts) = > {}

If your plug-in needs to change the Webpack configuration, please read this section in the Vue official CLI documentation.

Https://cli.vuejs.org/dev-guide/plugin-dev.html#service-plugin

Add dependencies through the generator

As mentioned above, the CLI plug-in generator can help us add dependencies and change project files.

Therefore, the first step we need to do is to add two dependencies for our plug-in: Rxjs and vue-rx:

Module.exports = (api, options, rootOptions) = > {api.extendPackage ({dependencies: {'rxjs':' ^ 6.3.3, 'vue-rx':' ^ 6.0.1,});}

A generator should output a function that takes three parameters: a GeneratorAPI instance, generator options, and-- if the user creates a project with some presets-- the entire preset is passed as the third parameter.

The api.extendPackage method extends the package.json of the project. Nested fields will be deeply merged unless you take * * {merge: false} * * as a parameter. In our example, we will add two dependencies to the dependencies section.

Now we need to change a main.js file. In order for RxJS to work in the Vue component, we need to import a VueRx and call Vue.use (VueRx).

First, let's create a string that we want to add to the main file:

Let rxLines = `\ nimport VueRx from 'vue-rx';\ n\ nVue.use (VueRx);`

Now we're going to use the api.onCreateComplete hook function. When a file is written to disk, it is called:

Api.onCreateComplete (() = > {/ / inject to main.js const fs = require ('fs'); const ext = api.hasPlugin (' typescript')? 'ts':' js'; const mainPath = api.resolve (`. / src/main.$ {ext}`);}

Here we are looking for the main file: if it is a TypeScript project, it will be main.ts, otherwise it will be a main.js file. Fs, this is the file system.

Now let's change the contents of the file:

Api.onCreateComplete (() = > {/ / inject to main.js const fs = require ('fs'); const ext = api.hasPlugin (' typescript')? 'ts':' js'; const mainPath = api.resolve (`. / src/main.$ {ext}`); / / get content let contentMain = fs.readFileSync (mainPath, {encoding: 'utf-8'}); const lines = contentMain.split (/\ r?\ nutf-8' g). Reverse (); / / inject import const lastImportIndex = lines.findIndex (line = > line.match (/ ^ import/)); lines [lastImportIndex] + = rxLines / / modify app contentMain = lines.reverse () .join ('\ n'); fs.writeFileSync (mainPath, contentMain, {encoding: 'utf-8'});});

We are reading the contents of the main file, dividing it into lines, and restoring its order. Then we search for the first line with the import statement and add our rxLines there. After that, we reverse the row array and save the file.

Test the CLI plug-in locally

Let's add some information about our plug-in to package.json, and then try to install it locally for testing.

The most important information is usually the plug-in name and version (these fields will be needed when publishing the plug-in to npm), and you can add more information at any time! a complete list of package.json fields can be found here. Here are my documents:

{"name": "vue-cli-plugin-tiantian", "version": "xxx.1.5", "description": "Vue-cli 3 plugin for adding RxJS support XXXX", "main": "index.js", "keywords": ["vue", "vue-cli", "rxjs", "vue-rx"], "author": "TianTian", "license": "MIT" }

Now is the time to check how our plug-ins work! To do this, we create a simple project supported by vue-cli:

Vue create test-app

Go to the project folder and install our newly created plug-in.

Cd test-app npm install-- save-dev file:/full/path/to/your/plugin / / enter the path

After installing the plug-in, you need to call it:

Vue invoke vue-cli-plugin-rx

Now, if you try to check the main.js file, you can see that it has changed.

Import Vue from 'vue' import App from'. / App.vue' import VueRx from 'vue-rx'; Vue.use (VueRx)

In addition, you can find your plug-in in the devDependencies section of your test application package.json.

Create a new component with the generator

When your plug-in works, it's time to extend its functionality so that it can create a sample component. It is time to extend its functionality and enable it to create sample components. Generator API uses the render method for this.

First, let's create this sample component. It should be a .vue file located in the project src/components folder. Create a template folder within the generator folder, and then simulate the entire structure in it:

Project catalog

Suppose that your sample component should be a single-file component of Vue with limited space, so this article explains RxJS in depth.

So a simple click counter with two buttons driven by RxJS is created, as shown in the figure:

Button

Now we need to instruct the plug-in to render this component when called. To do this, we add the following code to generator / index.js:

Api.render ('. / template', {... options,})

This renders the entire template folder. Now, when the plug-in is called, a new RxExample.vue will be added to the src / components folder.

Process user selection by prompting

What if the user does not want to have a sample component? Isn't it wise to let users decide during plug-in installation? This is the reason why the hint exists!

We have previously created the prompts.js file in the plug-in root directory. This file should contain an array of question: each question is an object with fields such as name, information, selection, type, and so on.

The name is important: we will use it later in the generator to create a condition for rendering the sample component.

Prompts can have different types, but check boxes and confirmations are the most widely used in CLI. We will use the latter to create a question with a "yes" answer.

So let's add the prompt code to prompts.js!

Module.exports = [{name: `addExample`, type: 'confirm', message:' Add example component to components folder?', default: false,},]

We have an addExample prompt that asks the user if they want to add the component to the components folder. The default answer is "no".

Let's go back to the generator file and make some corrections. Change the call to api.render to:

If (options.addExample) {api.render ('. / template', {... options,});}

We are checking to see if addExample has a yes answer, and if so, the component will be rendered.

Don't forget to reinstall and test your plugin after each change!

Publish

The points worthy of our attention are:

Before you release the plug-in, check that its name matches the schema vue-cli-plugin-

< YOUR-PLUGIN-NAME >

Match. This allows your plug-in to be discovered through @ vue / cli-service and installed through vue add.

Next you need to register a npmjs.com, and then follow the mechanism of sending the package to complete the next operation.

Of course, to release the plug-in, go to the plug-in root folder and type npm publish in the terminal.

At this point, you should be able to install the plug-in using the vue add command. Give it a try!

The above is how to build the Vue CLI plug-in, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report