Front end engineering development scaffold and packaging automation construction workflow

moranlj 2021-09-15 10:26:57

1、 Front-end engineering summary

Front-end engineering : It refers to following certain standards and specifications , Improve development efficiency through tools 、 Cost reduction is a means ; Widely concerned and discussed , The reason is : The functional requirements of the front end are continuously improved , Business logic is complex day and night ; From traditional websites 、H5、 Applet ;

1、 Problems in front-end development :

  • Want to use ES6+ New characteristics , But there's a problem with compatibility
  • Want to use Less、Sass、PostCSS enhance CSS The programmability of , But the running environment can't directly support
  • Want to use a modular way to improve the maintainability of the project , However, the operating environment cannot directly support
  • Before deploying online, you need to manually compress it into code and resource files , The deployment process needs to manually upload code to the server
  • Multi person collaborative development , We can't unify our code style , From the warehouse pull The quality of the code coming back is not guaranteed
  • Part of the function development needs to wait for the back-end service interface to complete in advance

2、 The main problems solved by front-end engineering :

  • Disadvantages of traditional language or grammar
  • You can't use modularity / Componentization
  • Repetitive mechanical work
  • Uniform code style 、 QA :
  • Rely on back-end service interface support
  • As a whole, back-end projects

3、 The performance of front-end engineering

The whole point of view : From the creation of the project -》 code -》 preview -》 Submit -〉 Deploy , Each link can improve efficiency through engineering ; say concretely ,

  • When you create the project , You can use scaffolding tools to automatically help us build the basic structure ; Create project structure and create specific types of files
  • code : With the help of Engineering tool automation Help us do some : formatting code 、 Check code style 、 compile 、 structure 、 pack
  • preview / test : In the traditional preview link, I pay attention to Apache's improvement web Basic services , Unable to provide heating update service ; Now you can use :Web Sever,Mock,
  • Submit : have access to Git Hooks/Lint- staged/ Continuous integration automates the inspection of project quality and style before code submission , Make sure you don't submit problematic code , Solved from the warehouse pull Come down with the problematic code
  • Deploy : Automatic release ,CI/CD, Avoid the wrong factors of manual operation

4、 Front end engineering performance details

engineering Is not the same as Some tool

The core of engineering : It should be for the overall project Planning and architecture , and Tools Just to help us Implementation planning and architecture A means of ;

image.png

  • Mature engineering tools

Items belonging to a specific type ( It's engineering integration ), The official integrated engineering scheme , such as :vue-cli Not only helped us create the project , More agreed vue What is the structure of the project , Some tools are provided : Hot update , Code style checking ; image.png

5、 Implement the of front-end engineering 5 In two dimensions :

  • Scaffold tool development
  • Build systems automatically
  • Modular packaging
  • Project code normalization
  • Automated Deployment

2、 The scaffold Tools

1、 The nature of scaffolding

Essential role : A tool for automatically creating a project file structure 、 Provide project specifications and conventions ; The same convention contains

  • The same organizational structure
  • The same development paradigm
  • The same module dependency
  • Same tool configuration
  • The same basic code

summary : The same agreement as above , So when building a new project , There will be A lot of repetitive work Want to do , Scaffolding tools are used to solve such problems ( Complex tools for solving projects ), You can quickly build a specific type of project skeleton through scaffolding tools , Start working based on this skeleton ;

give an example :IDE The process of creating a project It's a scaffolding workflow ;

Front end scaffolds are generally not integrated in one IDE in , Exist as a separate tool ;

2、 Common Scaffolding tools

  • react -> create-react-app
  • vue -> vue-cli
  • angluar ->angluar-cli

These tools are nothing more than Create the corresponding project infrastructure based on the information you provide ; They are It is applicable to the framework projects it serves ; Another category :

  • With Yeoman Scaffolding tools for representative general projects , They are based on a set of templates , Generate a corresponding project structure , Very flexible 、 Very easy to expand ;
  • Plop: Used to create specific types of files during project development ;

3、Yeoman Introduce

Definition : The official definition is : Create a modern web Scaffolding tools used ;Yeoman More like A scaffold runs on a platform , We can go through Yeoman Build different types of Generator To create any type of project ; We go through Generator Create your own projects , thus Custom build your own scaffolding ;Yeoman Its advantages are also its disadvantages : In the eyes of many people who focus on framework based development ,Yeoman Too generic, not enough focused , So they prefer to use things like vue-vli This kind of scaffold ;

4、Yeoman Basic use

  • 1、 install Yeoman: yarn global add yo
  • 2、 Install the corresponding Generator, Build different Generator type : For example, use Generator- node,

yarm g add generator-node

  • 3、 Use yarn Set up the project : New project folder , function yo node establish node project , Select the basic information of the project

5、Yeoman And Sub Genaerator

Create a specific type of file , such as :es6, babel, wait , Need this demand , have access to Sub Genaerator,

  • install :yo node:cli , rewrite package.json file , Add new modules and configurations , Appear one binde To configure :‘lib/cli.js’
  • Use the module as a global : yarn link , You can directly use the module name to execute the project

6、Yeoman Use steps to summarize

  • 1、 Identify your needs
  • 2、 Find the right Generator
  • 3、 Global installation found Generator
  • 4、 adopt yo Run the corresponding Generator
  • 5、 Fill in the options interactively through the command line
  • 6、 Generate the project structure you need

7、 Self defined Generator To create Generator

  • establish Generator : Namely NPM modular ;
  • Yeoman Of Generator The name of must be generator-<name>, The module cannot be found

image.png

  • install Generator: yarn add yeoman-generator Module
  • Create custom Generator Folder : generator->app->index.js, stay index.js Export a relay Yeoman Generator The type of ;

image.png

7、 Create files based on modules

image.png

8、Vue Generator Case study

  • 1、 Create a new Generator Catalog :mkdir generator-vue
  • 2、yarn init , initialization package.json
  • 3、 install Yeoman Dependence , yarn add yeoman-enerator
  • 4、 newly build Generator Main entry file for : generator->app->index.js, stay index.js Export a relay Yeoman Generator The type of ;

9、 How scaffolding works

Scaffolding tools are a CLI application . It is basically a command line interaction after starting the scaffold , According to the interaction results, combined with the template file, a basic project structure is formed .

1、 Develop a small CLI
  • mkdir sample-scaffolding
  • cd sample-scaffolding
  • yarn init --yes
2、 open package.json file , Add one bin Field .
 "name": "sample-scaffolding",
"version": "1.0.0",
"main": "index.js",
"bin": "cli.js",
"license": "MIT"
}
 Copy code 
3、 And then create this cli.js file
#!/usr/bin/env node
// Node CLI The application entry file must have such a header
// If it is Linux perhaps macOS The system also learns to modify the read and write permissions of this file
// Specifically through chmod 755 cli.js Implement modification
console.log('cli working')
 Copy code 
4、 On the command line through yarn link This module link To global
5、 Then run the command line :sample-scaffolding
6、 Use inquirer Do command line interaction , install yarn add inquirer
7、 The working process of scaffold cli.js
//1、 Ask users questions through command line interaction
//2、 Generate a file based on the result of the user's response
const inquirer = require('inquirer');
inquirer.prompt([
{
type:'input',
name:'name',
message:'Project name'
}
]).then(answer=>{
console.log(answer);
})
 Copy code 
8、 Execute on the command line sample-scaffolding, If the result can be returned, it indicates that the execution is successful
9、 Create a new template directory templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<%= name %>
</title>
</head>
<body>
</body>
</html>
 Copy code 
10、 newly build templates/style.css( The second template )
11、 You need to render files through the template engine , So install the template engine
yarn add ejs
 Copy code 
12、 Create a new file directory demo
13、 Execute... Under the command line of the new file directory sample-scaffolding, Will be in demo Directory to generate template files, rendered files
14、 Simple case complete code :
#!/usr/bin/env node
// Node CLI The application entry file must have such a header
// If it is Linux perhaps macOS The system also learns to modify the read and write permissions of this file
// Specifically through chmod 755 cli.js Implement modification
// console.log('cli working')
// The working process of scaffold :
// 1. Ask users questions through command line interaction
// 2. Generate a file based on the result of the user's response
// Use inquirer stay node Command line interaction with users
// yarn add inquirer
const path = require('path')
const fs = require('fs')
const inquirer = require("inquirer")
const ejs = require("ejs")
inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Project Name?'
}
]).then(answers => {
// console.log(answers)
// Generate files according to the user's answer results and templates
// Directory of templates
const tmpDir = path.join(__dirname, 'templates')
// Target directory
const destDir = process.cwd()
// console.log(process.cwd()) // D:\workPlatform\demos\sample-scaffolding
// Convert all the files in the template to the target directory
fs.readdir(tmpDir, (err, files) => {
if(err) throw err
files.forEach(file => {
// Render these files through the template engine
ejs.renderFile(path.join(tmpDir, file), answers, (err, result) => {
if(err) throw err
// console.log(result)
// Write the result to the destination file path
fs.writeFileSync(path.join(destDir, file), result)
})
})
})
})
 Copy code 

Automated build

1、 Introduction to automation

  • automation : Do the work by machine instead of by hand
  • structure : transformation , Convert one Dongxu into another
  • Automated construction in the development industry : Automatically convert the source code written in the development stage into the code or program that can be run in the generation stage , This transformation process is generally called automated build workflow ;
  • Automated build workflow functions : Problems caused by being out of compatibility with the operating environment ; Use efficient syntax during the development phase 、 Norms and standards ;
  • Application scenarios :
    • When developing a web page :ECMAScirpt Next Improve coding efficiency and quality
    • Sass: enhance CSS The programmability of
    • template engine : abstract HTML Duplicate code in
  • The role of automated build tools : Build transformations that are not supported characteristic ;

2、 Automate build NPM Script --- Build simple projects

  • install yarn add browser-sync --dev
  • stay package.json in ,
"scripts": {
"preserver": "yarn build",// Automatically build before startup Sass file
// Monitor the changes of files under the project , Automatically sync to browser
"serve": "browser-sync --files \"css/*.css\"",
"start":"run-p build serve" // At the same time build and serve
}
 Copy code 
  • Start project : yarn serve
  • install yarn add npm-run-all --dev

3、 Common automated build tools

  • Grunt: The plug-in ecosystem is perfect , But because the construction process is based on temporary files , The desired build speed is slow ; For example, use SACSS File construction , Compile first , Then add the prefix of free attribute , Finally, compress the code ; In the process ,grunt There are disk read and write operations in each step , such as : After compilation , Write the results to a temporary file , Then read the temporary file in a plug-in for the next step , thus , The more links you deal with , The more times you deal with it ; For mega projects , The more project files , The slower the build will be
  • Gulp: Common build tools , It's a good solution grunt The problem of slow construction speed , Because it is implemented based on memory , That is to say , The steps of processing files are completed in memory , Compared with the disk, the reading and writing speed is naturally much faster ; Multiple tasks are supported by default , The efficiency is naturally high , The way of use is more intuitive and easy to understand , The most current front-end building system ;
  • FIS: Recommended by Baidu front end ;FIS Like a bundle , Inherit the typical requirements of the project internally , such as : Processing resource loading 、 Modular development 、 performance optimization

Suitable for beginners FIS, Flexible requirements, suitable for gulp、grunt

Be careful : webpack: Strictly speaking , It's a packaging tool

4、grunt Basic use of

  • install grunt : yarn add grunt
  • Add... Under the project root directory : gruntfile.js file
//grunt Entrance file
// Used to determine some required results grunt Automated tasks
// You need to export a function
// This function receives a grunt Shape parameter , Internal provides some information that can be used when creating tasks API
moudle.exports = grunt=> {
grunt.registerTask('foo', () => {
})
grunt.registerTask('bar',' Task description ', () => {
})
// Perform the default task
grunt.registerTask(‘default’,['foo','bad','far'])
}
 Copy code 

5、grunt The marking task for failed

  • An error occurred in the logic of the build task , You can mark tasks ;
  • Use return false Mark tasks
  • Asynchronous tasks cannot be used return false return , Specify an argument
moudle.exports = grunt=> {
grunt.registerTask('bad', () => {
return false
})
}
 Copy code 

Enforce tasks : yarn grunt default -- force

5、grunt Configuration options API:initConfig

moudle.exports = grunt=> {
grunt.initConfig({
foo: 'bar',
far: {
bar: 123
}
})
grunt.registerTask('foo', () => {
console.log(grunt.config('foo'))
console.log(grunt.config('far.bar'))
})
}
 Copy code 

6、grunt Of Multi objective mission ( The subtasks )

  • Use registerMultiTask Definition
grunt.initConfig({
build: {
css: '1'
js: '2'
}
})
moudle.exports = grunt=> {
// Multi-objective configuration
grunt.registerMultiTask('build', function() {
console.log('build task')
})
}
 Copy code 

7、grunt Of The plug-in USES

  • Use loadNpmTasks

8、gulp Use

Core features : Efficient 、 Easy to use

  • Create an empty folder for the project
  • initialization package.json yarn init --yes
  • install gulp:yarn add gulp --dev
  • see node-modules/bin/gulp
  • Create a new one gulpfile.js
exports.foo = done => {
console.log('foo task working')
done() // Mark the completion of the task
}
 Copy code 

9、gulp Combined tasks of

Please bring the original link to reprint ,thank
Similar articles

2021-09-15

2021-09-15

2021-09-15

2021-09-15