This article has authorized the exclusive use of the public account of the Developer community, including but not limited to editing, marking the original rights and other rights.
Introduction to the
In my previous shared article summarizing some of the basic configuration packages developed by the Vue project team, we have addressed most of the common packages, from API protocols to the Model data layer. This behavior gives the project a more automated approach that allows the team front end engineer to focus less on generation. Focus only on code results and code quality to get more practical meaning.
At the same time, for code quality management at 7 clock 】 【 refactoring code several times after, I summarized some practice of front-end code optimization, we also mentioned the practice of some code optimization, and many conditions are good coding habits for developers to explore at the same time, the basic habits to become a better front-end engineer.
In this article. The main thing I want to share is what scaffolding and architecture can do for developers to improve their efficiency and fault tolerance.
The content of this article is not very difficult to read, and it does not involve some technical systems too deeply. It is suitable for most front-end readers to read and explore thinking.
What is an asset?
For us developers, the code we build is a personal asset, but most of the time, the management of the asset is very bad for the team, and for asset management, many small company projects are temporary, and every project belongs to zero. So, every time for all configurations, the encapsulation is different. For the team, there is no uniformity in all the projects. It takes a long time for new students to learn different configuration styles. In addition, if the boss is impatient and needs to put into production quickly, the project can not escape the fate of restructuring in the end.
, therefore, is of vital significance for public asset management team, the framework of the update will drive the update is the inevitable trend of assets, so this would require the team ability to have certain experience in maintenance of assets, after all assets maintenance is out from the project work but, revenue side is the front end of the whole department team.
What can Plop miniature scaffolding do?
In this case, I’m using Plop to manage the daily assets, for the components we write daily, method library, these fixed assets must be managed. For example, I wrote a small wechat program to handle the logon logical block, I extracted it into a separate slice method. So, the next time I write a little program, should I just copy the logical method over and call it?
Plop is a very small Sub Generator, and for us, it was integrated into the scaffolding of our project to act as a scheduler. It requires scheduling of development assets maintained by our own team, such as UI Desgin, Utils, Api schema generation, abstract code templates… And so on function scheduling production, greatly reduce the developer’s daily CV, plug-in some work.
- Create the corresponding UI asset component
- Create the corresponding asset method
- Create development-time API interface functions
- Create the development directory structure
- Create the development template code
- .
How does Plop implement these features?
At build time, all we need to do is configure the setGenerator to generate different process styles through the namespace, determining the behaviors and choices we currently need to deal with.
plop.setGenerator('test', createPageTemplate)
plop.setGenerator('api', createApiTemplate)
Copy the code
When we need to create a page, we need to run the plop command to create the corresponding page and components, instead of creating the file first and then creating the corresponding resources. Even more, we can configure other modes, as shown in the following figure, whether you need Modl, sASS, SCSS or not.
A simple setGenerator
A basic setGenerator can do more or less depending on what the developer wants it to do. Students who have learned C language should know the basic operation of the command line interface, through scanf to input, according to the input content to produce the corresponding logic out, in fact, this is very similar to scaffolding, but scaffolding do more things, in addition to the input box, there are lists, selectors… And the presence of other component elements.
So, let’s look at how the basic page container is created:
In a simple setGenerator, there are four configuration keys.
Comopnent: "Description: 'this is a skeleton plopfile', prompts: [], // array of inquirer prompts: [] // array of actionsCopy the code
comopnent
: Is the name of the namespace used as the setGeneratordescription
: Is used as a description to describe the current behavior to be handledprompts
: As a step bar prompt, you can prompt and interrupt to operate with the user and guide the user to configure.actions
: Is generated when users perform corresponding actions after the configuration is performed as prompted.
As you can see, the behavior of Plop is not very complicated, most of it is configurational work. Therefore, the off-season of the project cycle can be selected to do the asset generation mode. Here is an ordinary setGenerator that doesn’t have much behavior to go with it
How are pages generated?
Let’s do a Demo with a basic directory generation to route insertion example. The following is a basic demonstration, the main implementation of the project directory automatically built while inserting routes, one click to create a page level template. As shown in the figure below, after the moreTest page is generated, a route declaration will be automatically inserted under routes.js, achieving the purpose of one-click generation.
Install the plop
You can choose to install ploP’s running dependencies through the package manager in the form of a global installation or just a current project installation.
# shell
yarn global add plop
Copy the code
New Start Command
The yarn new module command is added using script. The name can be arbitrary. It is mainly used to execute Plop scripts.
// package.json
"scripts": {
"build": "vue-cli-service build"."lint": "vue-cli-service lint"."dev": "vue-cli-service serve --mode dev"."doc": "jsdoc -r -c conf.json README.md"."new": "plop"
},
Copy the code
Create plopfile
Plopfile.js is an entry file configured as plop, mainly loading different setGenerators. Since our setGenerator is likely to be large volume, it is recommended to split it into a directory to do this. Personally, I have put all the Settings in the. Setting directory for easy management.
In this case, it is an aggregation of files to declare the corresponding configuration and setGenerator Name. The main code is the action for each module.
const createPageTemplate = require('./src/.setting/plop/page')
const createApiTemplate = require('./src/.setting/plop/api')
function cli (plop) {
plop.setGenerator('page', createPageTemplate)
plop.setGenerator('api', createApiTemplate)
}
module.exports = cli
Copy the code
prompts
Before you write a prompt, you can read the document and view the configuration properties in the prompts. It is easier to achieve the corresponding prompt operations and options.
type
: Main types exist:input
.number
.confirm
.list
.rawlist
.expand
.checkbox
.password
.editor
name
: Specifies the name of the variable stored in the current type. You can obtain the corresponding operation value by the namemessage
: Prompt message, which is mainly presented to the userdefault
: Default value of the current optionchoices
: Multiple options, usually used for list display.other
: seePlop
Document, or others say I water#Plop Types
I have some basic parameters to explain, and I can begin to write a prompt. The code below creates an input, list, and confirm prompt component. Allow users to perform better operations.
prompts: [
{
type: 'input'.name: 'pageName'.message: 'Please enter a page folder name'
},
{
type: 'list'.name: 'cssType'.default: 'scss'.choices: ['manual'.'sass'.'scss'].message: 'Please select the type of SASS you want to create? '
},
{
type: 'confirm'.name: 'isModel'.default: true.message: 'Please select do you want to create Model? '},].Copy the code
action
If the input component is complete, then we can get the corresponding value in the action, which is the value after the user’s action, and we can add the action behavior through this.
There are several common actions.
add
: This action is used to add files to a project. The PATH attribute is a handle template that will be used to create files by name. The content of the file will be determined by the or attribute.addMany
: This action can be used to add multiple files to a project in a single action,add
An enhanced version of.modify
: This operation can be performed in two ways. Properties can be used to find/replace text in a specified file, and functions can be used to transform file contents.append
: this is used to append data to a file at a specific location, insert file data function.
Common attributes are:
type
Above:action
Type of actionpath
: Specifies the path to be operatedtemplateFile
: Template pathdata
: intohbs
The data in the template can be obtained from the template.
As you can see, below I get the value of the operation that the user entered, and according to the value of the operation, I perform the action. Here, for the sake of intuition, I don’t use addMany to create the file, but I do it step by step. In the following figure and code, we can generate the corresponding file directory, file name, and template code. It’s not hard to understand here, but it’s just a matter of adding a few actions with different judgments, and finally returning out of the collection array.
actions: data= > {
const { pageName, cssType, isModel } = data
console.log(data)
const actions = []
const name = '{{pageName}}'
const path = `src/${PAGE_PATH}/{{ pageName }}/`
if (pageName) {
actions.push({
type: 'add'.path: `${path}/index.vue`.templateFile: 'src/.setting/template/view/page.hbs'.data: {
name: pageName,
}
})
}
if(cssType ! = ='manual') {
actions.push({
type: 'add'.path: `${path}/index.${cssType}`.templateFile: 'src/.setting/template/view/css.hbs'})}if (isModel) {
actions.push({
type: 'add'.path: `${path}/model.js`.templateFile: 'src/.setting/template/view/model.hbs'.data: {
name: pageName,
}
})
}
actions.push({
type: 'append'.path: 'src/router/routes.js'.pattern: / \ [/,
templateFile: 'src/.setting/template/router/config.hbs'.data: {
name: pageName,
}
})
return actions
}
Copy the code
HBS template
You may have found that our template is HBS, which is a simple template engine. Compared with the current template, although its advantages are not obvious, we just need to write some templates, so HBS can fully meet some of our basic needs. We need to create the HBS template file that corresponds to the action declaration so that plop can be created or inserted into our declared path.
<template>
<div>
<p>Page created successfully, current page name -- {{name}}</p>
<p>-- @/views/{{name}}</p>
</div>
</template>
<script>
import { useServices } from 'framework'
const api = useServices()
export default {
name: '{{name}}'.data: () = >{}}</script>
Copy the code
The effect
With that done, we have a basic directory added, let’s see how it looks. Let’s see if what we end up inserting into the view is what we want.
Code = >
const PAGE_PATH = 'views'
module.exports = {
description: 'Create the file, noting that it must conform to the project constraint specification'.prompts: [{type: 'input'.name: 'pageName'.message: 'Please enter a page folder name'
},
{
type: 'list'.name: 'cssType'.default: 'scss'.choices: ['manual'.'sass'.'scss'].message: 'Please select the type of SASS you want to create? '
},
{
type: 'confirm'.name: 'isModel'.default: true.message: 'Please select do you want to create Model? '},].actions: data= > {
const { pageName, cssType, isModel } = data
console.log(data)
const actions = []
const name = '{{pageName}}'
const path = `src/${PAGE_PATH}/{{ pageName }}/`
if (pageName) {
actions.push({
type: 'add'.path: `${path}/index.vue`.templateFile: 'src/.setting/template/view/page.hbs'.data: {
name: pageName,
}
})
}
if(cssType ! = ='manual') {
actions.push({
type: 'add'.path: `${path}/index.${cssType}`.templateFile: 'src/.setting/template/view/css.hbs'})}if (isModel) {
actions.push({
type: 'add'.path: `${path}/model.js`.templateFile: 'src/.setting/template/view/model.hbs'.data: {
name: pageName,
}
})
}
actions.push({
type: 'append'.path: 'src/router/routes.js'.pattern: / \ [/,
templateFile: 'src/.setting/template/router/config.hbs'.data: {
name: pageName,
}
})
return actions
}
}
Copy the code
Retrospective historical articles
- After refactoring the code a few times, I have summarized some front-end code optimization practices
- To summarize, I shared some basic configuration packages developed by the Vue project team
- Practical thinking on how to use mixins in Vue to manage asynchronous data
- Summary of front-end interface request management in my project
conclusion
Plop can maintain a large number of template assets. With the increasing number of setGenerators, our asset library will become larger and larger. In addition to maintaining this part of the code, the design of scaffolding also needs to be detailed, and try to provide better element description on the interface. Allow new or entry-level developers on the team to use the asset based on the description, rather than looking through documents or asking for the asset provider.
Assets in the design are also important, we can try to interact with the UI and jointly maintain a system of cross section and the business assets, actually involved in the design of the system, the interaction, animation model are assets, the Plop can only bring common asset maintenance for development, but the team is also can be derived from foreign assets.
When accumulated assets reach a certain accumulation, to make new products, the development will greatly improve the efficiency, than from 0 to 1, and is more of a direct integration assets to development, at this time most of the design, interaction, animation, basic methods, components, have already exist in the asset library, we only need to be extracted, and then call on the page, We can have more time to method code for cyclomatic complexity and logic optimization above.
If this article has helped you, you can support the author with a like.