This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

Front-end engineering

  • What are the main problems that engineering solves? Technology exists to solve problems
    • Want to use es+ new features to improve coding efficiency, but compatibility issues
    • You want to use less/ Sass/PostCSS to enhance the programmability of CSS, but the runtime environment does not directly support it.
  • You want to use a modular approach to improve the maintainability of your project, but the runtime environment does not directly support it.
  • Before deploying online, you need to manually compress the code and resource files
  • The deployment process requires manually uploading the code to the server
  • It is impossible to unify the code style of everyone in the collaborative development, and there is no way to guarantee the quality of the code pulled back from the warehouse.
  • The development of some functional interfaces needs to wait for the completion of back-end service interfaces.

Summary:

1.A weakness of traditional language or grammar2.Modularity/componentization cannot be used3.Repetitive mechanical work4.Code style is uniform. Quality assurance5.Rely on back-end service interface support6.Overall reliance on back-end projectsCopy the code

In a word: solve problems and improve efficiency

engineering

All repetitive tasks should be automated

Or: the planning and architecture of the project

Create project --> Encode --> Preview/Test --> Commit --> Deploy Create project: Create project structure Create specific type of file Encoding: Format code. Verify the code style. Use new features. Compile/build/package preview/test: Web Server/Mock Live_reloading /HRM SourceMap(connection tool for developing code and running code) submit: Git hooks(Quality and style and commit logging)/Lint-staged/Continuous integration deployment: CI/CD automatic releaseCopy the code

Engineering does not equal tools

Tools are just a means to achieve engineering

  • Plan the overall workflow architecture of the project
    • Organization of files
    • Source code development paradigm
      • What syntax, what specification, what standard
    • What is the basis for the anterior and posterior separation
      • ajax
      • The middle layer
  • Mature engineered integration
    • create-react-app
    • vue-cli
    • angular-cli
  • Engineering doesn’t just help us create projects, it provides a lot of conventions and tools.

Engineering is the biggest contributor

nodejs

  • Almost everything we use is written in NodeJS

Scaffolding tool

  • The essential role of scaffolding

    • Create the project infrastructure and provide the project specifications and conventions
    • The sameThe structure of the organization Development paradigm Module is dependent on Tool configuration Based on the code
  • Build a specific type of project skeleton

yeoman

A universal scaffold running platform

We can use Yeoman with different generators to create any type of project. You can customize your own front-end scaffolding by creating your own Generaotr

Too generic and not focused, which is why the Vue/React CLI is so popular

  • Install the yeoman

npm install -g yo

  • With a specific generator. Different generators generate different projects

npm install -g generator-node

  • Create using commands

    yo node

The use of the yeoman

  1. Know your needs
  2. Find the appropriate Generator
  3. Install the found Generator at global scope
  4. Run the corresponding generator through Yo
  5. Enter options interactively on the command line
  6. Generate the project structure you need
  • For example, use generator-webapp
    • The installationyarn global add generator-webapp
    • Generating scaffoldyo webapp

It’s all general-purpose scaffolding

We now customize the generator

  • Build your own scaffolding based on Generator

  • The name of a scaffold created using Yemo-Generator must be Generator -<name>

  • yarn add yeoman-generator

    Create files and content using the wirte method

    • Note: The template format here must be consistent with the specification
  • Export as a global module package using NPM Link

  • Create a folder, and then use yo Sample to hold the template files generated by the generator

  • In this folder yo <name> name is the name of the folder you just created. It is related to the name of the folder, which must start with generator-, and name is the string without generator-

Instead of using the write method to write to the file, write to the template directly

const Generator = require('yeoman-generator')

module.exports = class extends Generator {
    writing() {
        // Yeoman automatically calls this method during the file generation phase
        // We are trying to write files to the generated directory
        // 1. Path 2
        // this.fs.write(
        // this.destinationPath('temp.txt'),
        // Math.random().toString()
        // )

        // Write the template to the file. Do not use the write method to dynamically create the file and write the content
        // Template file path
        const tmpl = this.templatePath('foo.txt')
        // Output the target path
        const output = this.destinationPath('foo.txt')
        // Template data context
        const context = {title: 'hello lhr'.success: false}
        // Output to target path by copyTpl method
        this.fs.copyTpl(tmpl, output, context)
    }
}
Copy the code

The template approach is much more efficient than creating each file manually, especially if there are many files.

How scaffolding works

When launched, you are asked preset questions, and your answers are combined with some template files to generate a template structure.

Write a simple scaffold

#! /usr/bin/env node

// The node CLI application entry file must have this folder
// In Linux or MacOS, you need to change the read/write permission of this file to 775
Chomd 775 cli.js
// The cli.js entry needs to be specified by the bib field in packJSON

const inquirer = require('inquirer')
const ejs = require('ejs')
const path = require('path')
const fs = require('fs')
inquirer.prompt([
    {
        type: 'input'.// The way of asking
        name: 'name'.// Ask which key the result (value) is stored by
        message: 'Project name? ' // The content of the problem}])// Generate a file based on the results of the user's answers
    .then(answers= > {
        console.log(answers)

        // Template directory
        const tmplDir = path.join(__dirname, 'templates')
        // The target directory
        const destDir = process.cwd() // nodejs Specifies the directory where the command is executed

        // Convert all files under the template to the directory directory
        fs.readdir(tmplDir, (err, files) = > {
            if (err) throw err
            files.forEach(file= > {
                // 1. file path 2. context in template 3. callback
                ejs.renderFile(path.join(tmplDir, file), answers, (err, result) = > {
                    if(err) throw err
                    // 1. Location to which to write 2fs.writeFileSync(path.join(destDir, file), result) }) }); })})// The working process of the scaffold
// 1. Ask the user interactive questions through the command line
// 2. Generate a file based on the answer results of the user
Copy the code

Automated build

Automate build workflow

Source code is automatically built into production code

Problems arising from compatibility with the operating environment

Use efficient syntax, specifications, and standards

  • The latest standard of ES
  • Sass delivers CSS programmability
  • Template engine. Reduce redundant code

Build and transform features that are not supported

Early experience
  • Convert sASS to CSS using the sASS official packager

    yarn add sass ./node_modules/.bin/sass scss/main.scss css/style.css

    Sass will be converted to CSS

  • Create an automated build workflow using NPM’s script

    Configure script properties in packJSON

    "scripts": {
       "sass": "sass scss/main.scss css/style.css"
    }
    Copy the code
  • Start a development server and open the current web page

    yarn add browser-sync

    "scripts": {
        "sass": "sass scss/main.scss css/style.css"."serve": "browser-sync ."
      }
    Copy the code
  • If we did not build the sass file before YARN serve, then it is incorrect

    Use the preserve attribute in the script. In this case, the yarn serve is executed first

    A. to do B. to do C. to do D. to do

    "scripts": {
        "sass": "sass scss/main.scss css/style.css"."preserve": "yarn sass"."serve": "browser-sync ."
      },
    Copy the code
  • Add the sASS file to add the listening mechanism

    "sass": "sass scss/main.scss css/style.css --watch"

  • Listening for changes in sass blocks browser-sync, so multiple tasks need to be performed

    yarn add npm-run-all

    Add the script command to allow both scripts to execute simultaneously.

    "scripts": {
        "sass": "sass scss/main.scss css/style.css --watch"."serve": "browser-sync ."."start": "run-p sass serve"
      },
    // Preserve needs to be removed
    Copy the code
  • Let browser-sync listen for file changes in the project

    "serve": "browser-sync . --files \"css/*.css\"".Copy the code

gulp

Install gulp development dependencies, add the glupfile.js file to the project root directory, and run the project on the terminal using the CLI provided by Glup

Combined gulP tasks
Gulp asynchronous tasks in three ways
Core principles of the build process
  • The file is read out, processed, converted, and finally written to another location

  • In the absence of a build system, we do that manually.

  • This is done through the original underlying Node file stream API

  • Read stream –> Transform logic –> write

Gulp —————— The streaming build system

Official definition: as a stream-based build system, GULP wants to implement the concept of a build pipeline. More extensions can be achieved.

Gulp file manipulation API and use of plugins
  • Gulp encapsulates node’s file operations (read streams, write streams). More powerful.

  • As for the transformation flow, it is mostly through plug-ins

  • In general, gulp implements the process of building tasks: first create the read stream through SRC method, then process the file through the transformation stream provided by the plug-in, and finally create the write stream through the dist method provided by GULp to write to the target file.

  • For HTML files in gulp-demo, use SWip to replace template data and configure all the data that needs to be configured.