2020 report card: development idea and Realization of front end scaffold

Time:2021-1-26

The biggest advantage of a small company is what is needed. PC/ official account / small program, front desk, backstage, middle stage, react, Vue and UI are all in touch. The demand for products is constantly increasing, and the more the project is done, the more people are still. For the standardization of the front-end, the requirement of engineering is higher and higher.

aotoo-hubAs a general-purpose front-end scaffold, it has no technology stack dependence and focuses on multi person cooperation and engineering. Can help developers quickly output projects, like tossing can study.

aotoo-hubIt is a full stack scaffold with integrated front-end / node design. The front-end is compiled with webpack4, and the node uses koa2 to provide services. Hub can be run independently as a front-end compilation tool, and can also cooperate with node side to deploy online services

Stand alone runtime, which is only used as a front-end compilation and output static resource tool. Hub compiles the front-end resources by using webpack. In the development mode, webpack dev server provides heat update support, and only produces compressed code in the production environment

Fusion runtime, node (koa2, KOA router) will take over webpack dev server to provide back-end services. At this time, SSR services and API services can be implemented, which can be used for deployment and online services

Some characteristics

  • Provides a simple command line tool
  • The compilation environment supports multiple projects, sharing compilation resources and nodes_ module
  • Support to provide compiling environment for react / Vue / JQ / native JS / small program
  • Standard directory structure of front end and node end
  • Support dynamic style (SASS / stylus)
  • Support multiple environments, command line switching, testing, production and other environments
  • Support node (koa2)

Scaffold source structure

Hub workspace
  ├── build
  ├── aotoo.config.js
  ├── index.js
  ├── package.json
  ├── postcss.config.js
  └── src
       #Vue project presentation
       └─ vueSample
             ι - configs # node environment configuration file, which contains default.js
             ├ -- dist # static resource output directory
             ├ - JS # front end business JS directory (front end)
                 │ - venders # third party library file directory + custom public library (front end)
                 ...
             └ - source directory of server # node
                   The service directory of pages # node
                   └ - plugins # custom plug in directory
                   
       #React project demo
       └─ reactSample
             ι - configs # node environment configuration file, which contains default.js
             ├ -- dist # static resource output directory
             ├ - JS # front end business JS directory (front end)
                 │ - venders # third party library file directory + custom public library (front end)
                 ...
             └ - source directory of server # node
                   The service directory of pages # node
                   └ - plugins # custom plug in directory
                   
       #Small program project demonstration
       └─ xcxSample 
             ...
             ...
             
       #Document project presentation
       └─ mdSample 
             ...
             ...

GITHUB
More information

Some ideas of developing hub scaffold

The front-end project architecture is more challenging than the back-end project architecture. Why? The general back-end architecture (most small and medium-sized projects) is stable in one environment, language and project, and may be updated once a few years. The front-end architecture needs to deal with multi terminal output, complex projects, multiple frameworks, complex components and so on. The framework update is very active, and it often feels like it’s hard to learn to give up.

Scaffolding as an important front-end tool, especially need to have a unified, standardized idea. Good scaffolding can make the development, testing, operation and maintenance work become very cool. We need scaffolding to constrain and standardize the project structure, have a unified compiling environment, decouple with the project, facilitate multi person collaboration, and be simple and out of the box. Developers only need to focus on business and develop on the basis of the generated project structure

Decoupling from project

Why do we need to decouple architecture and projects? Imagine that when there are n projects in a company, architects update and maintain scaffolds of different projects and frameworks, causing the risk of project instability. At the same time, it increases the time cost and communication cost of architects, developers, testers, operators and maintenance personnel.

Technology stack independent

There are many types of projects in the company, which are light-weight and need to be iterated online quickly. Generally, we use Vue; more complex projects are completed by multiple people. Generally, we use react; small program is also a popular front-end direction, and there are old JQ based projects, so scaffolding needs to be able to support the compilation of a variety of front-end frameworks

It’s not very difficult. It can be realized by adding the configuration required by various frameworks in webpack. Currently, hub supports react, Vue, angular, jQuery, applet and other technology stacks.

Multi project support

By decoupling architecture and project, a single project can be compiled and run independently or simultaneously. All projects share the compilation environment of hub workspace and the node of workspace_ module。 The project has its own dist directory, and a unique service port is assigned at startup. As shown in the figure below

working space
  ├── build
  └── src
       └─ vueSample
             └─ dist
       └─ reactSample
                └─ dist
       └─ mdSample
             └─ dist
       └─ xcxSample
             └─ dist

Command line tools

The command line needs to be concise and efficient, which can realize environment initialization, project initialization, development mode, production mode, environment switching, parameter transfer and one click deployment

Configuration

The command line and configuration file complement each other. Configuration can simplify the command line operation, such as starting multiple projects at the same time, setting the environment of a project, etc.

The following example is the specific configuration item of the hub project

{
  //Project name
  name: 'mdSample', 

  //Specify project version
  version: 1.0.8,  

  //Whether to start the project, the default is false
  //At startup, it is easy to enter the project name from the command line
  startup: true,    

  //Whether to start the node server or not, the default is false, which is provided by webpack dev server
  //For example, in the process of component development, close the node service to improve performance and efficiency
  server: false, 

  //Omit front-end compilation, default to false, need to set server = true
  //Only start the node side, the development mode improves the efficiency, and the production mode can be directly deployed
  onlynode: false, 

  //Project source directory
  src: path.join(ROOT, 'src/mdSample'),  

  //Specify the project port, otherwise assign random port
  port: 8400,

  options: {

    //Project gray environment, such as test, pre release, production, etc
    //It is recommended to use the command line -- config test to select the environment configuration
    // scenes: 'default' 
  }
},

version management

Environment and project isolation

Isolation is to be more focused and perform their own duties. Architects update the environment, developers update the business, and do not interfere with each other. The compilation environment and the project are decoupled. Using git can easily achieve this idea, as shown in the figure below

Workspace # = = > set environment git, ignore SRC/*
  ├── build
  └── src 
       └ - vuesample # = = > set Git

In order to enable the command-line tool to support the execution in the project source directory, developers can use vscode to just open the vuesample directory to start the development work.

#In the hub workspace directory  
Aotoo dev vuesample # running development environment

#In the project vuesample directory
cd src/vueSample
Aotoo dev vuesample can also start the development environment in the project source directory

Project version
The project version is based on the version of the configuration file, and all static resources of the project will be compiled todist/${version}Directory, multiple versions will have multiple directories to facilitate rollback, backup and other insurance operations, as shown in the figure below

├ - dist # output directory (front end)
    Version directory, according to the version field in the configuration
    └─ 1.0.8
        └ - Dev # Development Directory
            │── js/index.js
            │── html/index.html
             ...

Multi environment

Test1 environment, test2 environment, test3 environment… Scaffold specifies the current runtime environment configuration of the project through command line parameters, and can also set the configuration file to switch.

Now many companies use the cloud configuration center like Apollo, which is very inconvenient for developers. There are two solutions to consider. One is to use the command line to pass different parameters to make the project call cloud configuration or local configuration; the other is to create methods in the configuration file to automatically capture the cloud configuration when the project is initialized.

aotoo dev --config test1

Specification project directory

Designing reasonable, standard and flexible templates is very beneficial to the rationality of project structure, because we all set up directories around templates to produce resources, and any resources are ultimately used in templates.

Static resource of template

<html>
 <head>
  <link href="common.css" />
  <link href="[filename].css" />
 </head>
 <body>
 <div id="root"><%- root %></id>
  <script />
  <script />
  <script />
 </body
</html>
  • common.js The separated public JS code is extracted and injected by webpack compile time
  • vendors.js The third frame library and general library, corresponding to JS / vendors directory
  • common.css Public CSS, corresponding to CSS / common. [CSS | SCSS | style] file
  • [file name]. JS business JS, corresponding to the business directory / file name, as shown in user.js
  • [file name]. CSS business CSS, corresponding business directory / file name, as shown in user.css
  • The hub uses EJS to parse the template, which is parsed by node or webpack dev server

For example, the template in the above example is relatively standard, and it is easy to output the standard project directory structure, which is roughly as follows

 project
    ├── html
         └── index.html
    ├── css
         └── index.css
    └── js
         └── index.js

In the hub project, in most cases, we can omit the HTML directory and CSS directory (no additional requirements), and the directory structure can be simplified as follows

 project
    └── js
         └── index.js

As a hub project, it can run normally. When compiling, the hub will automatically generate templates, styles, nodes, etc. for the project.

Emulating the directory structure of small program
The directory structure of a hub project can also be set as an item applet or Vue, as shown in the following example

project
    └── js
         └── user 
              ├──  index.js   #Output service JS = > user.js
              ├──  index.css  #Output business CSS = > user.css
              └──  index.html  #Output business template = > user.html

On the entry of webpack

As I said earlier, templates are very important, but I chose the entry based on JS index to generate webpack. Here is an assumption, that is, every template page must contain a business JS.

The entry based on JS index has a natural affinity for webpack, and its corresponding template can be generated automatically by using webpack HTML plugins.

As a compilation entry, we can give more functions to the entry of webpack, such as compiling static resources for each trunk of the entry, generating node side routing, generating node side API, and so on.

reactSample
The structure of the reactsample directory is very simple, and its composition is as follows

reactSample
     ├── configs/ default.js  #Environment configuration is actually generated at compile time
     └── js/index/index.js

The resource files needed by the project are automatically generated at compile time, and the styles are injected by JS at run time. The production environment provides node services, and the development environment provides dev server services. The server provides template rendering, image routing, image API and other services. And these are just ordersnode index.jsIt’s OK

Multi page and single page

The ultimate goal, of course, is to achieve mpa-spa hybrid mode, that is, multi single page mode. H5 needs spa, and PC needs MPa + spa. MPa is very simple. The output pages of node are all independent pages. Just have a template. It is a natural MPa mode.

Hub workspace
  ├── mdSample
       ├─ dir1 # => page1.html
       ├─ dir2 # => page2.html
       └─ dir3 # => page3.html

Hub can also easily provide mpa-spa mode for react and Vue, which is the buf of hub scaffold

Node middle layer

The introduction of node can solve the problem

  • Cross domain
  • Independent deployment
  • Custom API
  • Mock service
  • seo

route

Mirror routing
The node routing built through the entry of webpack is called image routing, which can provide page rendering service and API data interface service

Schematic structure of image routing

reactSample
     └── js
          └── user/ index.js  #Front end
     └── server
          └── pages/user/ index.js  #Node end

#Access mirror route http://www.abc.com/user
#Request API data routing ajax.post ('/user', {...}).then(res)  
#Node controller file server / pages / user/ index.js

We know that koa2 is a typical MVC back-end model, with view corresponding to the template and model corresponding to the data layer (driven by business, mostly ajax data). Bind the trunk of the entry with the koa router to form a mirror routing relationship (one-to-one correspondence) with the front end, and output its controller file to handle get / post / put / delete and other transactions

Custom route
Some routes have nothing to do with the page, such as upload, API interface belongs to this kind of special route, so we also need to create custom routes manually through plugins

plug-in unit

Plug ins are used to create custom routes and function modules. Custom routes are described above.

The typical application of function module is database request. Generally, the controller layer needs to initiate database requests, and the plug-in binds the function modules to the context of KOA. Note that this process is a preprocessing process, and the controller layer is a run-time process. Therefore, as long as the controller layer needs, it can obtain the data processing module from the context of KOA to initiate the database request

Applet support

For small program projects, we need to control the output of webpack and not let it do superfluous things. The final output code is handled by wechat small program development tool

According to the 1:1 peer-to-peer output applet source code, only use webpack to deal with some small problems of the applet, such as markdown, dynamic style, HTML and so on. (the output will not generate redundant code of webpack), and hot update is supported

Using webpack to participate in small program compilation, we can use loader / plugins to realize some ideas, such as writing a loader and translating wechat small programs into other small programs. It’s just that the comparison table is a little troublesome, and the idea should be feasible

Compatible with old projects

I’m also a front-end old man. The years of the front-end picture are just around the corner. The pain of the front-end and back-end integrated development mode (Java rendering template) is that you need to build a Java environment, you need to know every ID in the template, and you know the complex structure of the template like the palm of your hand.

At the same time of scaffolding compilation, collect all resources and organize a resource file( mapfile.json ), including JS / HTML / CSS / image and other information. take mapfile.json Give it to the Java boss, give the static resource file directory (dist) to the operation and maintenance boss, and ask the Java boss to write a script to automatically match the static resources.

Own demonstration project

The project includes four demo demonstration projects (react / Vue / Applet / MD document system). Each project is an independent project and can realize resource exchange through the node side. Easy and fast to use each set of environment.

Vue demo

vueSample, empty project based on vue2.0, including simple project demonstration of Vue router

Vue’s demo project is not up to vue3.0, because the peripheral Library of vue3.0 is not stable at the time of development. You plan to let it fly for a while, or you can introduce it yourself,More information

React demo

reactSample, an empty project, containing a simple demonstration of react16.

Demo of small program

xcxSample, is the development of native wechat applets, which supports cloud development. The project includes our developed applets queryui library and related components. Clearing the related references is a complete official example code of applets.More information

  • Dynamic style support
  • Various plug-in support of webpack
  • Native wechat applet
  • Dynamic template construction
  • template less
  • Support hook method
  • Built in support of markdown rich text
  • Built in support for HTML rich text
  • Build from aotoo Library

MD document system

The document system is a complete demonstration of a hub environment, including front-end compilation, routing, node side image routing, plug-ins, MPA / spa applications, command line use, etc,More information

  • Full stack system
  • The front page of the column is provided by node.js Server side rendering (SSR), browser side rendering after reuse (CSR & SPA)
  • Column item is multi page application (MPA) switching page; menu item is single page application (SPA) switching route
  • User defined isomorphism method, fether / requiremerkdown, etc., fetcher front-end Axios construction, node end got construction
  • Simulating the front-end routing of small program, we can cut the code according to the routing, load JS file on demand, and support SSR
  • Imitate the life cycle of small program, make page code and component code have clearer function division
  • Template less, write as few templates as possible, and let JS implement the template logic (the core function of aotoo Library)
  • Support markdown
  • Support SEO, internal automatic solution in the browser side reuse server side rendering HTML and data, seamless transition
  • Multi scene, testing and production
  • Aotoo library construction (encapsulation Library of react, jQuery of react component)(explain)

directory structure

2020 report card: development idea and Realization of front end scaffold

aotoo-hubDirectory structure after installation

Hub workspace
  ├── build
  ├── aotoo.config.js
  ├── index.js
  ├── package.json
  ├── postcss.config.js
  └── src
       #Vue project presentation
       └─ vueSample
             ι - configs # node environment configuration file, which contains default.js
             ├ -- dist # static resource output directory
             ├ - JS # front end business JS directory (front end)
                 │ - venders # third party library file directory + custom public library (front end)
                 ...
             └ - source directory of server # node
                   The service directory of pages # node
                   └ - plugins # custom plug in directory
                   
       #React project demo
       └─ reactSample
             ι - configs # node environment configuration file, which contains default.js
             ├ -- dist # static resource output directory
             ├ - JS # front end business JS directory (front end)
                 │ - venders # third party library file directory + custom public library (front end)
                 ...
             └ - source directory of server # node
                   The service directory of pages # node
                   └ - plugins # custom plug in directory
                   
       #Small program project demonstration
       └─ xcxSample 
             ...
             ...
             
       #Document project presentation
       └─ mdSample 
             ...
             ...

explain

aotoo.config.js

Project configuration file, including project version, project type, project source directory and other configurations

apps: [
    {
      Name: 'reactsample', // project name
      Version: '1.0.1', // project version. Each project has its own version
      Startup: true, // start by default
      Server: false, // whether to provide node side services. By default, 'dev server' provides services
      Type: 'Web', // item type, 'MP' is the applet
      src:  path.join (root, 'Src / reactsample'), // source directory
      Micro: false, // microservice mode (under development, not perfect)
      Options: {// Project extension parameters
        Scenes: 'default' // the default project environment. The environment configuration file will be generated 
        Cloud: false, // does the applet project start in the cloud
      },
      Port: 8500 // Project port
    },
    
    {
      name: 'vueSample',
      ...
    },
    
    {
      name: 'xcxSample',
      ...
    }
  ],
}

Configs directory

This directory stores environment configuration, and the compiler will generate relevant configuration according to the environment parameters given by the command line, such as test environment (test = > 0 test.js )

aotoo dev --config test

Dist directory

This directory stores front-end compiled files, including version directory, development directory and production directory

├ - dist # output directory (front end)
    Version directory, according to the version field in the configuration
    └─ 1.0.8
        └ - Dev # Development Directory
            │── js/index.js
            │── html/index.html
             ...
            └──  mapfile.json  #Static resource image file

        └ - Pro # production catalogue
            │── js/index_ [hash]. JS # the production file will carry hash
             ...
            └──  mapfile.json  #Static resource image file

JS directory

The directory stores front-end JS source code, public JS source code, business JS source code

├─ js         
    │ - vendors # public JS
    └ - index # front end business directory
         │─  index.js   #Business = > dist // index.js
         │─  index.scss  #Style = > dist // index.css
         └─  index.html  #Template = > dist // index.html
         
    └ - shop # front end business directory
         │─  index.js   #Business = > dist // shop.js
         │─  index.scss  #Style = > dist // shop.css
         └─  index.html  #Template = > dist // shop.html

Compiling ideas
Compiler traverses business JS file and generates its supporting resources (HTML / CSS / node)

DLL packaging (vendors directory)
Here DLL packing refers to packingvendors.jsandcommon.jsIt should be noted that vendors is a set of independent webpack packaging process, which is not in the same process as business JS packaging and will generatedist/.../vendors.jsDocuments,common.jsThe split code from the business JS. amongvendors.jsFile does not support hot update

Business packaging
Business package takes JS file as the entry of webpack, and generates its related static resources through the loader module, such as the shop directory in the above example

JS / vendors directory

This directory stores common code or framework libraries, such asvendors/index.jsIf react or Vue is introduced into, it should be noted that the contents of this directory will be applied toNode end(if the server service is enabled), you must pay attention to the compatibility of both ends

Server directory

When you set the server parameter to true in the configuration, the compiler will automatically generate the server directory and send the back-end service to the serverwebpack-dev-serverTurn to services provided by node

Image routing server / pages
When you set the server parameter to true in the configuration, the compiler will traverse the entry (business JS) and mirror the controller file of its node side, such as the shop in the above example

server
  └─ pages
      └─ shop
          └─ index.js

Controller file provides rendering service, get and post interface service by default

Node plug in server / plugins
The directory needs to be generated manually. The plug-in supports custom routing and custom function modules

Command line tools

aotoo-cliAotoo hub is the command line development tool library of aotoo hub, which is used for installation and compilationMore information

System environment

  • mac osx
  • linux
  • I won’t support itwindowsBut the Linux subsystem of win10 can
  • node >= 12

INSTALL

npm install -g aotoo-cli
Aotoo - V # check whether the installation is successful

USAGE

Install a new hub space

init <dir>

#New XXX project
$ aotoo init xxx

New web project

create <dir>

Automatically create pc/h5/ official account and other web projects and start projects.

#New project
$ cd xxx
$ aotoo create projectName

The project directory will be created under the XXX / SRC directoryprojectName, input according to the promptY, enter to continue
After the installation, modify theaotoo.config.js, supplementary item description

New applet project

create <dir>

For creating an applet project

#New project
$ cd xxx
$ aotoo create minip_name

The project directory will be created under the XXX / SRC directoryminip_name, please entern
After installation, open theaotoo.config.js, add project description, restart project

Start your own project

After the installation, the SRC directory of hub contains four demonstration projects, which can be started by the following command

Start document project

#The document project belongs to the default project and can be started directly
$ aotoo dev

Start Vue project

$ aotoo dev vueSample

Start the react project

$ aotoo dev reactSample

Start applet project

After compiling, you need to use the small program development tool to open the directory indicated by the terminal yellow font

$ aotoo dev xcxSample

Working mode

dev [name]

Compile the development mode and start the service. The front end supports hot update

#Start up aotoo.config Startup project in apps in
$ aotoo dev

#Start specified project
$ aotoo dev project_name

dev-clean [name]

Compile the development mode, clear common / vendors and other DLL files, regenerate and start the service

$ aotoo dev-clean

#Starts the specified project and clears the cache of the project common
$ aotoo dev-clean project_name

dev-build [name]

Compile the development mode, clear common / vendors and other DLL files, regenerate, and do not start the service

$ aotoo dev-build

#Compile the specified project
$ aotoo dev-build project_name

Production mode

build [name]

Production mode, pure compilation output, no service startup

$ aotoo build

#Compile the specified project
$ aotoo build project_name

build-clean [name]

Production mode, clear common / vendors and other DLL files, and regenerate, do not start the service

$ aotoo build-clean

#Compile the specified project
$ aotoo build-clean project_name

deploy

Before deployment, you need to compile in production mode

aotoo build-clean project_name

start [name]

Production mode, start node service

$ aotoo start

#Compile the specified project
$ aotoo start project_name

Node startup

#Compile project, production mode
$ node index.js

#Start test environment
$ node index.js --config test

#Enter the source server directory to start  
$ cd src/project_name/server
$ node index.js

PM2 start

#Compile project, production mode
$ aotoo build-clean project_name

#Start test environment
$ pm2 start index.js -- --config test

Extend param extension parameter

--config <name>

Specify the environment configuration file and use it together with the node side

#Development mode, start the test environment
aotoo dev --config test

#Production mode, start test environment  
aotoo build --config test

--name <name>

Start the specified project. This parameter can start multiple projects at the same time

#Start the project of XXX and YYY at the same time
$ aotoo dev --name vueDemo --name reactDemo

GITHUB
More information

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]