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 front-end scaffolding tools in web development

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

Share

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

This article mainly introduces how to build front-end scaffolding tools in web development, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

Preface

In the actual development process, building the structure of the project from scratch is a headache, so a variety of scaffolding tools emerge as the times require. The author uses more yoeman,express-generator and vue-cli is one of them. They are rich in functions, but the core function is to quickly build a complete project structure, developers only need to develop on the basis of the generated project structure, which is very simple and efficient.

As a person who will die without trouble, after being familiar with the methods of use, he began to ponder over their principles. After careful study of documents and source code, I finally figured out its core principle, and based on this principle, I built a scaffolding called SCION.

Now let's take SCION as an example to build our own scaffolding tool from scratch.

Core principle

Yoeman-generator is required for yoeman construction project. Yoeman-generator is essentially a project template with a complete file structure, and users need to manually download these generator locally, and then yoeman will automatically generate different projects based on these generator.

Vue-cli provides a wealth of options and settings, but its essence is also to pull different templates locally from a remote repository, rather than some "locally generated" cool techs.

From this point of view, the idea is to first create different template projects, and then the scaffolding refers to the template project according to the user's instructions to generate the actual project. The template project can be built into scaffolding or deployed in a remote warehouse. For a wider range of applications, SCION adopts the second approach.

Technology selection

Node.js: a fundamental part of the entire scaffolding tool, the latest version is recommended.

Es6: the new version of node.js already has very high support for es6, and using es6 can greatly improve development efficiency and development experience.

Tools developed by commander:TJ to better organize and process command-line input.

Asynchronous process control tool developed by co:TJ to write asynchronous code in a more comfortable way.

Co-prompt: or the work of the great god TJ. The traditional command line can only enter all the parameters and options on a single line at a time. Using this tool, you can automatically provide prompt information and receive user input step by step, similar to the step-by-step process of entering parameters in npm init.

Overall architecture

It is an international practice to understand the overall structure before embarking on development. Look at the picture:

First of all, understand the concept of template. A template is a template for a project that contains the complete structure and information of the project.

The template information is stored in a file called templates.json.

Users can add, delete and list templates.json through the command line.

By selecting different templates, SCION will automatically pull the corresponding templates from the remote warehouse to the local to complete the construction of the project.

Finally, the file structure of the whole scaffolding is as follows:

=

| | bin |

| | scion |

| | command |

| | add.js |

| | delete.js |

| | init.js |

| | list.js |

| | node_modules |

| | package.json |

| | templates.json |

Entry file

First set up the project, write the dependency in package.json and execute npm install:

"dependencies": {

"chalk": "^ 1.1.3"

"co": "^ 4.6.0"

"co-prompt": "^ 1.0.0"

"commander": "^ 2.9.0"

}

Create a\ bin folder in the root directory and create a scion file without a suffix in it. This bin\ scion file is the entry file for the entire scaffolding, so we'll write it first.

The first is some initialization code:

#! / usr/bin/env node-- harmony

'use strict'

/ / define the file path of the scaffolding

Process.env.NODE_PATH = _ _ dirname +'/.. / node_modules/'

Const program = require ('commander')

/ / define the current version

Program

.version (require ('.. / package') .version)

/ / define how to use

Program

.usage ('')

As you can see from the previous architecture diagram, scaffolding allows users to enter four different commands. Now let's write about how to deal with these four commands:

Program

.command ('add')

.description ('Add a new template')

.alias ('a')

.action () = > {

Require ('.. / command/add') ()

})

Program

.command ('list')

.description ('List all the templates')

.alias ('l')

.action () = > {

Require ('.. / command/list') ()

})

Program

.command ('init')

.description ('Generate a new project')

.alias ('i')

.action () = > {

Require ('.. / command/init') ()

})

Program

.command ('delete')

.description ('Delete a template')

.alias ('d')

.action () = > {

Require ('.. / command/delete') ()

})

The specific use of commander will not be expanded here, you can go directly to the official website to see the detailed documentation.

Finally, don't forget to process the parameters and provide help information:

Program.parse (process.argv)

If (! program.args.length) {

Program.help ()

}

The complete code can be found here.

Run this file using node and see the output below, proving that the entry file has been written.

Usage: scion

Commands:

Add | an Add a new template

List | l List all the templates

Init | i Generate a new project

Delete | d Delete a template

Options:

-h,-- help output usage information

-V-- version output the version number

Processing user input

Create a\ command folder under the root of the project to store command processing files.

Create a templates.json file in the root directory and write the following to store the template information:

{"tpl": {}}

Add templat

Enter\ command and create a new add.js file:

'use strict'

Const co = require ('co')

Const prompt = require ('co-prompt')

Const config = require ('.. / templates')

Const chalk = require ('chalk')

Const fs = require ('fs')

Module.exports = () = > {

Co (function * () {

/ / receive the parameters entered by the user step by step

Let tplName = yield prompt ('Template name:')

Let gitUrl = yield prompt ('Git https link:')

Let branch = yield prompt ('Branch:')

/ / avoid repeated additions

If (! config.tpl [tplName]) {

Config.tpl [tplName] = {}

Config.tpl [tplName] ['url'] = gitUrl.replace (/ [\ u0000 -\ u0019] / g,'') / / filter unicode characters

Config.tpl [tplName] ['branch'] = branch

} else {

Console.log (chalk.red ('Template has already existedwaters'))

Process.exit ()

}

/ / write template information to templates.json

Fs.writeFile (_ _ dirname +'/.. / templates.json', JSON.stringify (config), 'utf-8', (err) = > {

If (err) console.log (err)

Console.log (chalk.green ('New template added!\ n'))

Console.log (chalk.grey ('The last template list is:\ n'))

Console.log (config)

Console.log ('\ n')

Process.exit ()

})

})

}

Delete templat

Similarly, create the delete.js file under the\ command folder:

'use strict'

Const co = require ('co')

Const prompt = require ('co-prompt')

Const config = require ('.. / templates')

Const chalk = require ('chalk')

Const fs = require ('fs')

Module.exports = () = > {

Co (function * () {

/ / receive parameters entered by the user

Let tplName = yield prompt ('Template name:')

/ / Delete the corresponding template

If (config.tpl [tplName]) {

Config.tpl [tplName] = undefined

} else {

Console.log (chalk.red ('Template does not customers'))

Process.exit ()

}

/ / write to template.json

Fs.writeFile (_ _ dirname +'/.. / templates.json', JSON.stringify (config), 'utf-8', (err) = > {

If (err) console.log (err)

Console.log (chalk.green ('Template deleted'))

Console.log (chalk.grey ('The last template list is:\ n'))

Console.log (config)

Console.log ('\ n')

Process.exit ()

})

})

}

List template

Create the list.js file:

'use strict'

Const config = require ('.. / templates')

Module.exports = () = > {

Console.log (config.tpl)

Process.exit ()

}

Build a project

Now it's time for our most important part-- the build project. Similarly, create a new file called init.js in the\ command directory:

'use strict'

Const exec = require ('child_process'). Exec

Const co = require ('co')

Const prompt = require ('co-prompt')

Const config = require ('.. / templates')

Const chalk = require ('chalk')

Module.exports = () = > {

Co (function * () {

/ / process user input

Let tplName = yield prompt ('Template name:')

Let projectName = yield prompt ('Project name:')

Let gitUrl

Let branch

If (! config.tpl [tplName]) {

Console.log (chalk.red ('\ n × Template does not exitals'))

Process.exit ()

}

GitUrl = config.tplename [tplName] .url

Branch = config.tplename [tplName] .branch

/ / git command to pull the project remotely and customize the project name

Let cmdStr = git clone ${gitUrl} ${projectName} & & cd ${projectName} & & git checkout ${branch}

Console.log (chalk.white ('\ nStart generating...'))

Exec (cmdStr, (error, stdout, stderr) = > {

If (error) {

Console.log (error)

Process.exit ()

}

Console.log (chalk.green ('\ n√ Generation completed'))

Console.log (\ ncd ${projectName} & & npm install\ n)

Process.exit ()

})

})

}

As you can see, this part of the code is also very simple, and the key sentence is

Let cmdStr = git clone ${gitUrl} ${projectName} & & cd ${projectName} & & git checkout ${branch}

Its function is to clone from the remote repository to a custom directory and switch to the corresponding branch. Students who are familiar with the git command should understand that it is time for those who are not familiar with the command to make up lessons!

Global use

In order to use it globally, we need to set it in package.json:

"bin": {

"scion": "bin/scion"

}

When debugging locally, execute it in the root directory

Npm link

You can bind the scion command to the global, and then you can directly start with scion without typing long commands such as node scion.

Now that our scaffolding tools have been built, let's give it a try.

Usage test

Add | an add template command

Init | I generate project command

Delete | d Delete template command and list | l list template command

It's done! Now that our entire scaffolding tool has been built, we only need to know the git https address and branch of the template to continue to add to the SCION. If you work as a team, you only need to share the templates.json file of SCION.

Postscript

It takes a lot of thought to build things that don't seem complicated from scratch. The biggest problem is that at the beginning, I don't know how to deal with user input step by step like npm init, only a command line with all the parameters, which is a really bad user experience. After studying vue-cli and yoeman, I couldn't find the corresponding code, so I had to keep google. Finally, I found an article that can be realized with co and co-prompt. I once again worship the omnipotent TJ God. I also hope that I can have a partner to tell me how to achieve them in vue-cli.

This scaffolding has only the most basic functions, and it is far from reaching the height of similar products on the market. Fill it slowly in the future. Anyway, you have really learned a lot in the process of completing SCION.

Thank you for reading this article carefully. I hope the article "how to build front-end scaffolding tools in web development" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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