This is the 75 th original article without water, if you want to get more original articles, please search our official account to follow us. This article was first published in the cloud blog: Goodbye to copy and paste: Dynamic template generation tips

preface

In daily development, we need to constantly create new pages and components. Take the Vue project as an example. When creating a new page, we need to go through the same process over and over again:

1. Create a new folder

Create a.vue file and write

3. If your page has multiple components, create a Component folder and repeat the previous two steps

4. Finally, our business code

Assuming it takes a minute to create a new page and copy and paste the template code, a project with 60 pages would take an hour to write the repetitive, boring, and boring code. This is definitely not what we want to see, so here are a few tips for improving your performance.

Custom Snippets based on Vscode blocks

With the Snippets of Vscode we can customize the Snippets to quickly generate Snippets.

  • Open Vscode and click file – preferences – user code snippets

Snippets of grammar

Prefix: Snippet name, which is entered to invoke the snippetbodyThis is the body of the code snippet. The code you need to write is hereThe $1: Initial cursor position after code generation$2: The second position of the cursor after the code is generated. Press TAB for quick switching and can also have $3, $4, $5.. The ${1, character}: the initial cursor position after generating code (where1The character indicates that the cursor will select the character directly after the code is generated.description: code snippet description, the prompt displayed by the editor after entering the name TAB key :\t newline :\ r or \nCopy the code

Take vue.json as an example:

{
	"Print to console": {
		"prefix":"vue"."body": [
			"<template>"."\t<div>test</div>"."</template>"."<script>"."export default{"."\tmounted(){$1},"."\tcomponents: {},"."\tdata() {"."\t\treturn {"."\t\t};"."\t},"."}"."</script>"."<style lang='less'>"."</style>"]."description": "vue-template"}}Copy the code

The effect is shown as follows:

File templates based on ploP customization

Plop features are based on Inquirer and Handlebars.

To put it simply, plop is a lightweight scaffolding that generates the required template by pre-configuring the page template to be generated and accepting the specified parameters on the command line.

  • Install PLOP in the project

npm install --save-dev plop

  • Create one in the project root directoryplopfile.js
module.exports = function(plop){
  plop.setGenerator('test', {// Test is a self-defined name that is used when executing the command line
      description: 'generate a test'.// Here is the function description of this plop
      prompts: [{type: 'input'.// The type of problem
          name: 'name'.// The question corresponds to the variable name of the answer, which can be used in actions
          message: 'view name please'.// A problem at the command line
          default: 'test' // The default answer to the question}].actions: data= > {
          const name = '{{name}}';
          const actions = [
          {
              type: 'add'.// Operation type, here is add file
              path: `src/views/${name}/index.vue`.// Path to the template generation
              templateFile: 'plop-templates/view/index.hbs'.// The path to the template
              data: {
                name: name
              }
          }
        ];
        returnactions; }}); }Copy the code
  • Create the Plop-templates folder in the root directory and create an index.hbs in the plop-templates/view folder
<template>
  <div />
</template>

<script>
  export default {
    name: '{{ properCase name }}'.props: {},
    data() {
      return{}},created(){},mounted(){},methods: {}}</script>

<style lang="less">

</style>
Copy the code
  • The new script

Add it to package.json

"script": {... ."new":"plop"
}
Copy the code
  • runnpm run new

At this point, a simple fixed template is automatically generated.

The plop into the order

At this point we can generate fixed templates, so the problem is that some folders need.less files and some don’t. How do we dynamically configure them?

Without further ado, let’s look at examples.

/ / plopfile. Js file
module.exports = function(plop){
  plop.setGenerator('test', {description: 'generate a test'.prompts: [{type: 'input'.name: 'name'.message: 'Please enter folder name'}, {type: 'input'.name: 'less'.message: 'Need less files? (y/n)',}],actions: data= > {
        const name = '{{name}}';
        let actions = [];
        if (data.name) {
          actions.push({
            type: 'add'.path: `src/${name}/index.vue`.// Where the file was generated
            templateFile: 'plop-templates/view/index.hbs'.// Template path
            data: {
              name: name
            }
          });
        }
        if (data.less === 'y') {
          actions.push({
            type: 'add'.path: `src/${name}/index.less`.// Where the file was generated
            templateFile: 'plop-templates/index.less'.// Template path})}returnactions; }}); }Copy the code

At this point, we can dynamically configure the number of files, so the problem arises again, in a page sometimes need navigation bar, sometimes do not need navigation bar, how to solve this situation?

/ / plopfile. Js file
module.exports = function(plop){
  plop.setGenerator('test', {description: 'generate a test'.prompts: [{type: 'input'.name: 'pageName'.message: 'Please enter folder name'}, {type: 'input'.name: 'less'.message: 'Need less files? (y/n)'}, {type: 'confirm'.name: 'hasNavbar'.message: 'Do you need a navigation bar? (y/n)'.default: this.hasNavbar
        }
      ],
      actions: data= > {
        const { pageName, less, hasNavbar } = data;
        const name = '{{pageName}}';
        let actions = [];
        if (pageName) {
          actions.push({
            type: 'add'.path: `src/${name}/index.vue`.templateFile: 'plop-templates/view/index.hbs'.data: {
              name: name,
              hasNavbar: hasNavbar, // Whether there is an action button}}); }if (less === 'y') {
          actions.push({
            type: 'add'.path: `src/${name}/index.less`.templateFile: 'plop-templates/index.less'})},returnactions; }}); }Copy the code
/ / HBS file
<template>
  <div>
    {{#if hasNavbar}}
      <div>The navigation bar</div>
    {{/if}}
  </div>
</template>

<script>
  export default {
    name: '{{ properCase name }}'.props: {},
    data() {
      return{}},created(){},mounted(){},methods: {}}</script>

<style lang="less">

</style>
Copy the code

The effect is shown as follows:

conclusion

This article mainly introduces a few simple new file template tips, every day a improve small skills, on time off work is not a dream! If there is a better way, feel free to comment in the comments section.

reference

Say goodbye to typing template, automatically generate base Template (Vue)

VScode – Custom snippets

Automatically generate.vue files based on PLOP using the command line

Recommended reading

Brief analysis of vue-Router source code and dynamic routing permission allocation

Write high quality maintainable code: comments at a glance

, recruiting

ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 40 front-end partners, with an average age of 27, and nearly 30% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and netease, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.

If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]