2020 transcript: development idea and implementation of front-end scaffold

The biggest advantage of working in a small company is to do everything. The PC/ official account / applet, front desk, back desk, middle desk, react, vue and UI are all in contact. There is a constant demand for products, more and more projects, and there are still a few people. For the standardization of the front end, the requirements of engineering are higher and higher.

As a general-purpose front-end scaffold, aotoo hub has no dependence on technology stack and focuses on multi person cooperation and engineering. It can help developers produce projects quickly. Those who like to toss can study it.

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

When running independently, it is only used as a tool for front-end compiling and outputting static resources. hub uses webpack to compile the front-end resources. In the development mode, webpack dev server provides heating update support, and only compressed code is output in the production environment

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

Some features

  • Provides simple command line tools
  • The compilation environment supports multiple projects and shares compilation resources and nodes_ module
  • Support the compilation environment for React/Vue/Jq / native js / applet and other projects
  • Standardized front-end and node end directory structure
  • Support dynamic styles (sass/stylus)
  • Support multiple environments, command line switching, testing, production and other environments
  • Support node side (koa2)

Scaffold source code structure

hub working space
  ├── build
  ├── aotoo.config.js
  ├── index.js
  ├── package.json
  ├── postcss.config.js
  └── src
       # vue project demonstration
       └─ vueSample
             ├── configs # node environment configuration file, including 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)
                 ...
             └── server    # Source directory of node
                   │── pages  # Business directory on node side
                   └── plugins # Custom plug-in directory
                   
       # react project demo
       └─ reactSample
             ├── configs # node environment configuration file, including 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)
                 ...
             └── server    # Source directory of node
                   │── pages  # Business directory on node side
                   └── plugins # Custom plug-in directory
                   
       # Applet project demo
       └─ xcxSample 
             ...
             ...
             
       # Document project presentation
       └─ mdSample 
             ...
             ...

GITHUB
More instructions

Some ideas of hub scaffold development

The front-end project architecture is more challenging than the back-end project architecture. Why? Generally, the 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. However, the front-end needs to deal with multi-terminal output, complex projects, multiple frameworks, complex components, etc. the updating of the framework is also particularly active, and there is often the feeling of being unable to learn and want to give up.

As an important front-end tool, scaffold especially needs a unified and standardized idea. Good scaffolding can make development, testing, operation and maintenance work very cool. We need scaffolding to restrict and standardize the structure of engineering projects; Have a unified compilation environment; Decoupling from the project; Facilitate multi person collaboration; It should also be simple and be used out of the box. Developers only need to focus on the business and develop on the basis of the generated project structure

Decouple from the project

Why is it necessary 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, resulting in the risk of project instability. At the same time, it increases the time cost and communication cost of architects, developers, testers, operation and maintenance personnel and operators.

Technology stack independent

There are many types of projects in the company, which are light-weight and require rapid iteration on-line. Generally, we use vue; A complex project completed by many people. Generally, we use react; Small programs are also a popular direction of the front end, and there are old jq based projects. Therefore, scaffolds need to be able to support compiling a variety of front-end frameworks

This is not very difficult. It can be realized by adding the configuration required by various frameworks in webpack. hub currently supports technology stacks such as React, Vue, Angular, Jquery, applet and so on.

Multi project support

Decouple the architecture from the project, that is, a single project can be compiled and run independently or run at the same time. 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. It can realize environment initialization, project initialization, development mode, production mode and environment switching. It can pass parameters and support one click deployment

Configuration

The command line and configuration file complement each other, and none of them is missing. 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 shows the specific configuration items of the hub project

{
  // entry name
  name: 'mdSample', 

  // Specify project version
  version: 1.0.8,  

  // Whether to start the project. The default is false
  // At startup, you can simplify the command line entry of project names
  startup: true,    

  // Whether to start the node server. The default is false. The service 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 the front-end compilation. The default is false. You need to set server=true
  // node only deployment mode can improve production efficiency
  onlynode: false, 

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

  // Specify the project port, or assign a random port if not specified
  port: 8400,

  options: {

    // Project gray environment, such as testing, 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 respective duties. Architects update the environment, developers update the business, do not interfere with each other, and the compilation environment is decoupled from the project. Using git can easily realize this assumption, as shown in the following figure

working space  # ==>Set the environment git and ignore src/*
  ├── build
  └── src 
       └─ vueSample # ==>Set project git

In order to enable the command-line tools to be executed in the project source code directory, developers can use vscode to just open the vueSample directory and start development without distractions.

# Under the hub workspace directory  
aotoo dev vueSample # Running development environment

# Under the project vueSample directory
cd src/vueSample
aotoo dev vueSample # You can also start the development environment in the project source code directory

Project version
The project version is based on the version of the configuration file. All static resources of the project will be compiled into the dist/${version} directory. Multiple directories will exist in multiple versions to facilitate rollback, backup and other insurance operations, as shown in the following figure

├─ dist          # Output directory (front end)
    │─ 1.0.1     # 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, Scaffolds can specify the current running environment configuration of the project through command line parameters, or set the configuration file to switch.

Many companies now use cloud configuration centers such as apollo, which is very inconvenient for developers. There are two options to consider: one is to use the command line to pass different parameters to make the project call cloud configuration or local configuration; Second, when the project is initialized, create methods in the configuration file to automatically grab the cloud configuration.

aotoo dev --config test1

Specification project directory

A reasonably designed, standardized and flexible template is very beneficial to the rationality of the project structure, because we all build a directory around the template to produce resources, and any resources are ultimately used on the template.

Static resource of template

<html>
 <head>
  <link href="common.css" />
  <link href="[filename].css" />
 </head>
 <body>
 <div id="root"><%- root %></id>
  <script src="vendors.js" />
  <script src="common.js" />
  <script src="[filename].js" />
 </body
</html>
  • common.js separated public JS code is extracted and injected by webpack during compilation
  • vendors.js third box rack library and general library, corresponding to js/vendors directory
  • common.css public CSS, corresponding to CSS / common [css|scss|style] file
  • [ filename ].js business JS, corresponding business directory / file name, such as user js
  • [ filename ].css business CSS, corresponding business directory / file name, such as user css
  • hub uses ejs to parse the template, and node or webpack dev server parses the template

For example, the above example template 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. The hub will automatically generate templates, styles, node s, etc. for the project at compile time.

Directory structure of imitation applet
The directory structure of the hub project can also be set as an applet or Vue, as shown in the following example

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

About webpack entry

I just said that the template is very important, but I chose to generate the weback entry based on the JS index. Here is a hypothetical premise, that is, each template page must contain a business JS.

The entry built based on JS index has natural affinity for webpack. You can use webpack HTML plugins to automatically generate its corresponding template.

As a compilation entry, we can give more functions to the entry of webpack, compile its static resources, generate node side routes, generate node side APIs for each trunk of the entry, and so on.

reactSample
The directory structure of reactSample, a demonstration project of hub, is very simple, as follows

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

The resource files required 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 a command node index JS is ok

Multi page and single page

Of course, the ultimate goal is to realize MPA-SPA mixed mode, that is, multi page mode. H5 needs SPA and PC needs MPA+SPA. MPA is very simple. The pages output from the node end are independent pages. Just have a template. It is a natural MPA mode.

hub working space
  ├── 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 node side can be introduced to solve the problem

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

route

Mirror routing
The node route built through the entry of webpack is called mirror route. Mirror route can provide page rendering service and API data interface service

Schematic structure of mirror 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. The view corresponds to the template and the model corresponds 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 with the front end (one-to-one correspondence), and output its controller file to handle GET/POST/PUT/DELETE and other transactions

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

plug-in unit

The plug-in is used to create custom routes and create function modules. Custom routes are described above.

The typical application of function module is database request. The controller layer generally needs to initiate a database request, and the plug-in binds the function module to the context of koa. Note that this process is a preprocessing process, while the operation of the controller layer belongs to the runtime process. Therefore, as long as the controller layer needs it, it can obtain the data processing module from the context of koa to initiate the database request

Applet support

For small program projects, we should control the output of webpack and don't let it do superfluous things. The final output code is processed 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 applet compilation, we can use loader/plugins to realize some ideas, such as writing a loader to translate wechat applet into other applets. It's just a little troublesome to compare the table. The idea should be feasible

Compatible with old projects

I'm also a front-end old man. The years of front-end cutaway are looming in front of me. The pain point 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 back of your hand.

While compiling the scaffold, collect all resources and organize a resource file (mapfile.json), including JS/HTML/CSS/IMAGE and other information. Set mapfile Give JSON to the java boss, give the static resource file directory (dist) to the operation and maintenance brother, and ask the java boss to write a script to automatically match the static resources.

Self contained demonstration project

The project includes 4 sets of DEMO demonstration projects (REACT/VUE / Applet / MD document system). Each project is not only an independent project, but also can realize resource interworking through the node. Convenient and quick to start each set of environment.

Vue DEMO

vueSample, based on vue2 0's empty project, including Vue router simple project demonstration

Vue's demo project is not on vue3 0, because vue3 The library around 0 is not stable yet. I plan to let it fly for a while. You can also introduce it yourself, More instructions

REACT DEMO demo

reactSample, an empty project, contains a simple demonstration of REACT16.

DEMO applet DEMO

xcxSample is a native wechat applet development that supports cloud development. The project includes our developed applet library queryUI library and related components. Clearing the relevant references is a complete official example code of the applet. More instructions

  • 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 of HTML rich text
  • Built by aotoo Library

MD document system

Here we will focus on the document system, which 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 instructions

  • Full stack system
  • The front page of the column is composed of node JS for server-side rendering (SSR), browser-side reuse post rendering (CSR & SPA)
  • The column item is the switching page of multi page application (MPA); The menu item is single page application (SPA) switching routing
  • User defined isomorphism method, ether / requiremarkdown, etc., construction of axios at the front end of the Fetcher, and construction of got at the node end
  • The front-end route of imitation applet can cut the code according to the route during construction, load js files as needed, and support SSR
  • Simulate the life cycle of small programs to make the function division of page code and component code clearer
  • template less, write as few templates as possible, and hand over the template logic to JS (the core function of aotoo Library)
  • Support markdown
  • It supports SEO and automatically solves the problem of reusing html and data rendered by the server on the browser side and seamless transition
  • Multi scenario, testing and production are available
  • aotoo library construction (react encapsulation library, react component jquery)( explain)

directory structure

Directory structure after aotoo hub installation

hub working space
  ├── build
  ├── aotoo.config.js
  ├── index.js
  ├── package.json
  ├── postcss.config.js
  └── src
       # vue project demonstration
       └─ vueSample
             ├── configs # node environment configuration file, including 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)
                 ...
             └── server    # Source directory of node
                   │── pages  # Business directory on node side
                   └── plugins # Custom plug-in directory
                   
       # react project demo
       └─ reactSample
             ├── configs # node environment configuration file, including 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)
                 ...
             └── server    # Source directory of node
                   │── pages  # Business directory on node side
                   └── plugins # Custom plug-in directory
                   
       # Applet project demo
       └─ xcxSample 
             ...
             ...
             
       # Document project presentation
       └─ mdSample 
             ...
             ...

explain

aotoo.config.js

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

apps: [
    {
      name: 'reactSample', // entry 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. The default is' dev server '
      type: 'web',        // Item type, 'mp' is applet
      src: path.join(ROOT, 'src/reactSample'), // Source directory
      micro: false,       // Micro service mode (under development, not perfect)
      options: {          // Project extension parameters
        scenes: 'default',// The default project environment generates an environment configuration file 
        cloud: false,     // Does the applet project start the cloud
      },
      port: 8500          // Project port
    },
    
    {
      name: 'vueSample',
      ...
    },
    
    {
      name: 'xcxSample',
      ...
    }
  ],
}

configs directory

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

aotoo dev --config test

dist directory

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

├─ dist          # Output directory (front end)
    │─ 1.0.1     # 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 be hash ed
             ...
            └── mapfile.json # Static resource image file

js directory

This directory stores front-end JS source code, public JS source code and business JS source code

├─ js         
    │─ vendors # Public JS
    └─ index # Front end service directory
         │─ index.js  # Business = > dist // index. js
         │─ index.scss # Style = > dist // index. css
         └─ index.html # Template = > dist // index. html
         
    └─ shop # Front end service directory
         │─ index.js  # Business = > dist // shop. js
         │─ index.scss # Style = > dist // shop. css
         └─ index.html # Template = > dist // shop. html

Compiling ideas
Traverse the business compiler (HTML / node / CSS) and generate its supporting resources

dll packaging (vendors directory)
Here, dll packaging refers to packaging vendors JS and common JS, it should be noted that vendors is an independent webpack packaging process, which is not in the same process as business JS packaging, and will generate dist // vendors.js file, common JS comes from the separation code of business JS (split of webpack). Including vendors JS file does not support hot update

Business packaging
For example, the business module uses the static webloader as the related directory, and generates the related directory of the business module through the JS P loader

js/vendors directory

This directory stores general code or framework libraries, such as in vendors / index When react or vue is introduced into JS, it should be noted that the contents of this directory will be applied to the node side (if the server service is enabled), so we 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 turn the back-end service from webpack dev server to the service provided by node

Mirror 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 on its node side, such as the shop in the above example

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

The controller file provides rendering services, GET and POST interface services 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 cli is the command line development tool library of aotoo hub, which is used for installation and compilation More instructions

System environment

  • mac osx
  • linux
  • windows is not supported, but 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 class project

create <dir>

Automatically create web projects such as pc/h5/ official account and start the project

# New project
$ cd xxx
$ aotoo create projectName

The project directory projectName will be created in the xxx/src directory. Enter Y according to the prompt and press enter to continue
After installation, modify aotoo config. JS, supplementary project description

New applet project

create <dir>

For creating applet projects

# New project
$ cd xxx
$ aotoo create minip_name

The project directory minIP will be created in the xxx/src directory_ Name, please enter n when prompted
After completing the installation, open aotoo config. JS, supplement the project description and restart the project

Start your own project

After the installation, the src directory of the hub contains four demonstration projects, which can be started respectively through the following commands

Start document project

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

Start VUE project

$ aotoo dev vueSample

Start REACT project

$ aotoo dev reactSample

Start applet project

After compilation, you need to use the applet development tool to open the directory indicated by the yellow font of the terminal

$ aotoo dev xcxSample

Working mode

dev [name]

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

# Start aotoo Startup items in apps in config
$ aotoo dev

# Start the specified project
$ aotoo dev project_name

dev-clean [name]

Compile in development mode, clear dll files such as common/vendors, regenerate, and start the service

$ aotoo dev-clean

# Start the specified project and clear the cache of the project common
$ aotoo dev-clean project_name

dev-build [name]

Compile in development mode, clear dll files such as common/vendors, 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]

In production mode, clear dll files such as common/vendors and regenerate them without starting 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

# Compilation project, production mode
$ node index.js

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

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

pm2 start

# 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, which is used 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 projects of xxx and yyy at the same time
$ aotoo dev --name vueDemo --name reactDemo

GITHUB
More instructions

Tags: node.js Front-end Webpack

Posted by sw9 on Mon, 02 May 2022 13:36:24 +0300