background

Students who use VUE for development must be familiar with VUE-CLI. In the early days of vue-cli@2x, we usually modified webpack to meet the needs of our team, or maintained a scaffold by ourselves to meet the daily development.

Plugins were provided after vuE-CLI was upgraded to 3X. Cli plug-ins, as part of VUe-CLI, provide us with a convenient development environment. They make our development environment plug-in, so that we can customize different plug-ins according to different situations, such as vue-cli-plugin-typescript vue-cli-plugin-vant.

So how to implement such a CLI plug-in?

vue-cli-plugin-kg-request

We decided to implement a VUE-cli-plugin-kg-Request in order to build our own wrapped requests into the project when it was initialized. Here is a basic directory structure:

├ ─ ─ the README. Md ├ ─ ─ index, js# service plugin    └ ─ ─ package. JsonCopy the code

The Service plugin mainly modifies the WebPack configuration

module.exports = (api, opts) = >{}Copy the code

throughgeneratorAPIGenerate template

An implemented directory structure

.├ ── Bass.md ├── Generator │ ├─ index.js# generator│ └ ─ ─ the template# plugins template file│ ├─ ├─ ├─ ├.js# sevirce plugin └ ─ ─ package. JsonCopy the code

The generator allows you to inject dependent fields into package.json or add files to a project. The api.extendPackage method extends package.json. By default, this method merges existing dependencies. If you want to do so, you can set the parameter merge: false.

// generator/index.js 
module.exports = (api, options, rootOptions) = > {
  api.extendPackage({
    dependencies: {
      "axios": "^ 0.18.0." "}})}Copy the code

Write the template file for later injection into the project we create. Here encapsulated the common data request method, set up a request interception, response data interception

// /src/plugins/request.js

import axios from 'axios'
import querystring from 'query-string'

// Request an interception callback
const requestInterceptors = function(config) {
  if (config.method.toLocaleUpperCase() === 'POST') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.data = querystring.stringify(config.data)
  }
  return config
}

// Respond to interception callback
const responseInterceptors = function(response) {
  let { data } = response
  // ..
  return Promise.resolve(data)
}

// Respond to intercepting error callback
const responseErrorInterceptors = function (error) {
  try {
    let { status } = error.response

  } catch(err) {
    console.error(JSON.stringify(err))
  }

  return Promise.reject(error)
}

const instance = axios.create()

instance.defaults.withCredentials = true

instance.interceptors.request.use(requestInterceptors)

instance.interceptors.response.use(responseInterceptors, responseErrorInterceptors)

export default instance
Copy the code

Modify the main js

After importing the template, we also import it in the entry file to avoid manual operation. To do this, use the FS module, read the entry file main.js, and write the text.

// generator/index.js 
 api.onCreateComplete((a)= > {

    // Add string
    const iviewLines = `\nimport request from '@/plugins/request'\n\nVue.use(request)`
    // Get the file contents
    let contentMain = fs.readFileSync(api.entryFile, { encoding: 'utf-8' })
    // Reverse the content
    const lines = contentMain.split(/\r? \n/g).reverse()
    // Find the subscript of import
    const importIndex = lines.findIndex(line= > line.match(/^import/))
    // Add an import statement below the first import reversal
    lines[importIndex] += iviewLines
    // Return to main
    contentMain = lines.reverse().join('\n')
    // Write the entry file
    fs.writeFileSync(api.entryFile, contentMain, { encoding: 'utf-8'})})Copy the code

When api.render is called, the generator will use EJS to render the files in./template.

// generator/index.js 
// Render the template
api.render('./template')
Copy the code

debugging

Debug. After we write it, we debug our code locally to test whether it meets.

Create a new project
vue create plugin-test

Enter the project directory
cd plugin-test

# Install vuE-CLI plug-in locally
npm install file://localPath/vue-cli-plugin-kg-request

# cli calls
vue invoke vue-cli-plugin-kg-request
Copy the code

release

Vue-cli plug-in can be published to NPM for more people to use, here is just a simple example, you can according to their own needs, expand the implementation of their own development environment plug-in, assembly, need to note that the name of the plug-in must be such as vue-cli-plugin-

, In case vue add can pull it. The official documentation

# Log in to your NPM account
npm login

# release
npm publish
Copy the code

Pay attention to our