Advanced front-end of the road: front-end architecture design (1) - the core code

Like many people I could, for the first time to hear the "front-end architecture" is the word, the first reaction is: "? There are front-end architecture that say" back-end development in the field of system planning and scalability is critical, therefore architecture division attracted increasing attention, long before development work started, they were invited to join the project, and they will discuss with the client architecture requires the platform to be built, but also the use of what technology stack? What type? how do these elements are Creating? software architect role is to ensure that every step of the project carried out under the guidance of the overall architecture, and not a random decision.

Front-end architecture

Now the front end of the field, with the wealth of JS framework, UI framework and library, front-end architecture has become very important. If a large-scale project has no reasonable front-end architecture design, the front-end code may be because different developers casual the introduction of various libraries and UI framework, leading to an abnormal amount of code becomes bloated, the end result may be unable to maintain the code becomes, poor performance page, a last resort only to overthrow the reconstruction, so we need before the start of the project, the same need for front-end code architected, once the front-end architect to design a testing mechanism for all front-end developer must follow, to establish a standardized system design, the project will have a standard measure code quality, front-end developers can enjoy more efficient work flow Therefore, the definition of front-end architecture can be summarized by the following sentence:

Front-end architecture is a set of tools and processes designed to improve the quality of front-end code and achieve efficient and sustainable workflows.

This series of front-end architecture articles, respectively revolve around four core front-end architecture, namely the code, processes, testing, documentation.

Four core front-end architecture

(A) Code

In the final analysis, all of the sites are a bunch of text files and resource files When we are faced with a lot of code generated by the production site, you will find the code and resources to set an expectation of how important it is in the code section we will focus on system architecture to achieve if the HTML, CSS, JavaScript.

(B) Process

Now long past the age FTP upload files, then the important thing now is to think how to use the tools and processes to build an efficient and avoid errors workflow workflow become more complex, those same is true for their tools. these tools are brought in to improve the productivity, efficiency and speed up the code to maintain the consistency of amazing results, but also accompanied by over-engineering and abstraction of risk. Therefore, the existing workflows that need to change.

(C) test

To build a scalable and sustainable system optimization, we must ensure that the new code and legacy code can be well compatible with our code does not they are part of a larger system of independent existence, create extensive test program coverage, can ensure that old code is functioning normally.

(D) documents

In general, if not the key member of the team to leave, we almost never aware of the importance of the document. Until that happens, we will have to stop the work at hand, priority to preparing all documents. Agency as a front end division , you should be good to write good documentation at the same time of project development.

Core Code

(One) HTML

In front of the architecture, as a basis for HTML page is very important. If the initial HTML is poorly, going to write a lot of unnecessary CSS and JavaScript to make up. Conversely, if the initial HTML if written well enough, you can write scalable and maintainable CSS and JavsScript based.

First we look at some of the primary front-end engineer may write HTML code:

<div id="header" class="clearfix">
  <div id="header-screen" class="clearfix">
    <div id="header-inner" class="container-12 clearfix">
      <div id="nav-header" role="navigation">
        <div class="region" region-navigation>
          <div class="block block-system block-menu">
            <div class="block-inner">
              <div class="content">
                <ul class="menu">
                  <li class="first leaf">
                    <a href="#">菜单1</a>
                  </li>
                  <li class="second leaf">
                    <a href="#">菜单2</a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

Such " divLuandun" code is a lot to cope with the primary front-end work cut pages to write out. Psd simply to restore the map, but you do not fully consider the HTML readability and maintainability.

Then, after HTML5, semantic tags by all the attention, using semantic tags, not only increases the readability of the code, but also conducive to SEO. Use semantic HTML tags, which is required in the front-end architecture Taking into account, let's look at the language of the label to write this code:

 <header>
    <section>
      <nav>
        <ul>
          <li>
            <a href="#">
              菜单1
            </a>
          </li>
          <li>
            <a href="#">
              菜单2
            </a>
          </li>
        </ul>
      </nav>
    </section>
  </header>

But if our page menu several times 10, it will add extra <li><a href="#">菜单N</a></li>, such repetitive work can give Mustachethis kind of template engine to solve, has been the template engines syntax Vue in to write HTML, it will reduce a lot of workload:

<template>
  <header>
    <section>
      <nav>
        <ul>
          <li v-for="(item, index) in navList" :key="index">
            <a href="#">
              {item}
            </a>
          </li>
        </ul>
      </nav>
    </section>
  </header>
</template>

<script>
    export default {
        data() {
          navList:['菜单1','菜单2','菜单3','菜单4','菜单5','菜单6','菜单7','菜单8','菜单9','菜单10']
        }
    }
</script>

You can also use Handlebars, Jade, artTemplate various template engine to your project, of course, these are required depending on the technology front-end selection of pre-selected architect. As a front-end architects need to assess the process of generating HTML you to order content, elements, and CSS class names used are much control? change these elements in the future it will be much more difficult? ease of use of the template? you can make changes through the system, or the need to manually handle? by answering these questions, it may subvert the way to build your own HTML and CSS.

(B) CSS

There are a lot of building CSS sophisticated methods, such as using the new namespace, expand or data attributes defined in the CSS JavaScript inside. You can find the shadow of these methods from BootStrap, ElementUI such UI framework. The following describes three kinds of commonly used method.

1.OOCSS method (Object-Oriented CSS object oriented CSS)

  <div class="toggle simple">
    <div class="toggle-control open">
      <h1 class="toggle-title">标题</h1>
    </div>
    <div class="toggle-details open">
      详细内容
    </div>
  </div>

The code above will show you how to create a switchable OOCSS method of HTML code, OOCSS There are two main principles:

  • Separation structure and appearance
  • Separation vessel and the contents

Structure and appearance of separation
herein toggleis used to control the structure, simpleto control the appearance, structure and appearance which is the separation performance. This allows the appearance of multiplexing, such as the current simpleskin at right angles, and the complexskin may be rounded corners, also added shadow.

Separation vessel and contents
used here toggle-titleis the performance of the separation container and contents, whether toggle-titlethe container is used <h1>or <h2>, or <div>, when combined with the toggle-titleclass name, then the name of such containers have been defined style presentation content.

2.SMACSS method (Scalable and Modular Architecture for CSS modular architecture scalable CSS)

<div class="toggle toggle-simple">
    <div class="toggle-control is-active">
        <h2 class="toggle-title">标题2</h2>
    </div>
    <div class="toggle-detail is-active">
        详细内容
    </div>
</div>

The code above basically shows how SMACSS method, in my personal understanding, OOCSS more actually provide a CSS construct of thought, the idea requires the structure and appearance of the separation, the separation of content and container. But does not provide a complete set of CSS build specification, SMACSS is to provide a system style, the style system has five specific categories:

  • Basics: If you do not add CSS class name to mark what would appear appearance
  • Layout: The page is divided into some regions
  • Module: modular design, the reusable unit
  • Status: described in the particular state or condition, or a display method of the layout module
  • Topic: An optional visual appearance of the layer that lets you switch to a different theme

basis

//base.css
body, form {
    margin: 0;
    padding: 0;
}

a {
    color: #039;
}

a:hover {
    color: #03F;    
}

On the basis of the code, it should be specified in some common style pages, for example, bodythe marginand paddingis set to 0, set the acolor of the label. Similar to some commonly used initial.cssfiles.

layout

//layout.css
#header, #article, #footer {
    width: 960px;
    margin: auto;
}

#article {
    border: solid #CCC;
    border-width: 1px 0 0;
}

Herein refers to the layout of the page layout of some common components, such as the head, the sidebar, the body and the bottom of these. These components will be in more than one page layout general, it is best to put it into a file css. easy reuse. in SMACSS, it is recommended to set the top label layout container is id, this ensures that each page has a unique layout container to hold the style, it is also easy to use css and js selector. of course, you also You can use a unique class name replacement id.

Module

//module.css

//module1
.module1 > h2 {
    padding: 5px;
}

.module1 span {
    padding: 5px;
}

//module2
.module2 > h2 {
    padding: 10px;
}

.module2 span {
    padding: 10px;
}

Module refers to the page can be separated and individually extracted multiplexing portion, such as a navigation bar, sidebar, the dialog box or some other widget. Therefore, prohibit the use of the module id, but rather by way of the class name.

status

<div id="header" class="is-collapsed">
    <form>
        <div class="msg is-error">
            There is an error!
        </div>
        <label for="searchbox" class="is-hidden">Search</label>
        <input type="search" id="searchbox">
    </form>
</div>

State is responsible for defining the different elements of a state, the presented pattern. The above section of code, already is-at the beginning of the name of the class is represented by state is-collapsed, is-errorother class name is not used alone, but the previous layout and modules used together. the following code is used with the module and a status bar tab:

//state.css
.tab {
    background-color: purple;
    color: white;
}

.is-tab-active {
    background-color: white;
    color: black;
}

theme

// module-name.css
.mod {
    border: 1px solid;
}

//theme.css
.mod {
    border-color: blue;
}

The theme here understood as the skin more appropriate, has the above code, for example, in module-name.cssdefined border styles in addition to colors, in theme.cssthe definition of the color of the border file, this advantage is, if you define the class name other colors to cover these styles have a color, then you can go to switch the color of the skin by the class name. reached the replacement theme effect.

More about SMACSS method, please refer to: https://smacss.com/book

3.BEM method (Block Element Modifier Modifier block element)

<div class="toggle toggle--simple">
    <div class="toggle__control toggle__control--active">
    <h2 class="toggle__title">标题3</h2>
    </div>
    
    <div class="toggle__details toggle__details--active">
        ...
    </div>
    ...
</div>

BEM is named for a CSS method proposed by Yandex, the method requires the use of a CSS class name, as far as possible using the following three components:

  • Block Name: Name of the component
  • Elements: element name at block inside
  • Modifier: any relevant elements associated with the block or modifiers

Block name
where many beginners will block name that is inline-blockthe block where the block name in fact refers to a separate module or component, for example a <header>can be used as a module, <header>the <nav>may be used as a module between modules can be nested with each other. in the sample code above, toggleit is a separate module

Element
element means can not be used in other portions of the block name in the BEM method, with the use of the elements after the block name __connection, the reason is because the double-underlined agree to use single underlined convenience named block names. In the sample code above, of toggle__control, toggle__titleis naming the block name + elements.

Modifier
modifier and SMACSS in a state similar to the BEM method, requires the use of modifier element behind --the connection. Some people feel that such an approach would make the code redundancy, SMACSS use is-activecan also represent the same role, and why to use the above code toggle__details--active? does in fact, if we look at the individual openand is-activethese two names, we do not know what they mean, but when you see a toggle__details--activeclass name, we know that it is: the name of this element is details, position in the toggleassembly, the state active.

(三) JavaScript

1. Select the frame
here I do not want to fall into Angular, React, fight three major framework of Vue. Vue I'm a developer, I know MVVM framework to our developers brought great convenience, do not have to stop jQuery in the form of DOM operations to develop, but only concerned with changes to the data, the data is changed to drive the DOM. this can devote more time to put the business logic processing.

On the current framework of the three major ecosystems, most of the business framework to implement the three actually not much difference, choose the frame more depending on preferences and learning costs of the project team members, such as learning costs of Vue it is much smaller compared to the Angular though I Vue is a developer, but I have to say in the use JSX React syntax allows to write code becomes very enjoyable.

Here I would like to say is: In fact, you probably do not need any frame!

There are many successful website is only used a number of template syntax, plus create from Sass files and dozens of small amount of Javascript functions manually created. When a large enough scale projects, the need to sacrifice in exchange code file size of the volume carried by the frame time to improve development efficiency, and then consider what kind of assessment introduced JS framework and UI framework, do not give up easily streamline the program.

2. Select a JavaScript code specifications

Each person is different way to write code, some people might like to use ==, but some like to use ===; some people might be accustomed to the use of each variable varto declare, but some prefer to use a varcomma operator to simultaneously declare more variables. the code used to run the program may not have an impact, but in large businesses, when faced with multiple developers to develop, if you do not have a standardized code, then the situation will be difficult to maintain the code, appears difficult to read. in order to join the new team members can quickly become familiar with the relevant code, and the code can make maintenance a Javascript code specifications regardless of the development of large projects and small projects, is essential.

If the company does not regulate the code to customize your own code, you can use the code specifications developed by large companies, where we recommend the following three code specifications to you:

Airbnb JavaScript Style Guide
Airbnb's Javascript is known as "the most reasonable way to write JavaScript code", is the Internet's most popular JavaScript code specification, which has 60,000 star foot on Github, covering almost every language features of JavaScript.

Ogle JavaScript Style Guide
Google's JavaScript code standards compared to Airbnb code specifications more comprehensive, not only from the beauty of the code, and code angle performance characteristics Js write the code were the norm, but also name the Js, the import way, Js code documentation were the norm. in the Introduction, the Google team showed that all use Google's Js specification in the project, to be called the Google Style code!

JavaScript Standard Style Guide
standard JS is a powerful JavaScript code specifications, comes linter and automatic code correction, no configuration, automatic formatting codes can be found in low-level error code in the early code. This code specification was adopted by many well-known companies, such as NPM, GitHub, mongoDB and so on.

The following specification taken ES5 portion of airbnb, to compare the use of standards and specifications do not use differences:
Array
  • Creating an array with direct amount
//bad
var items = new Array()

//good
var items = [];
  • Copying the array, usingslice
var len = items.length;
var itemsCopy = [];
var i;

// bad
for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
itemsCopy = items.slice();
  • Used sliceto convert an object into an array of arrays based
function trigger() {
  var args = Array.prototype.slice.call(arguments);
}
String
  • Single quotes ''wrapping string
//bad 
var name = "LITANGHUI"

//good
var name = 'LITANGHUI'
  • Generating a string using programmable joinconnection instead of using a connector. Especially the IE
var items;
var messages;
var length;
var i;

messages = [{
  state: 'success',
  message: 'This one worked.'
}, {
  state: 'success',
  message: 'This one worked as well.'
}, {
  state: 'error',
  message: 'This one did not work.'
}];

length = messages.length;

// bad
function inbox(messages) {
  items = '<ul>';

  for (i = 0; i < length; i++) {
    items += '<li>' + messages[i].message + '</li>';
  }

  return items + '</ul>';
}

// good
function inbox(messages) {
  items = [];

  for (i = 0; i < length; i++) {
    // use direct assignment in this case because we're micro-optimizing.
    items[i] = '<li>' + messages[i].message + '</li>';
  }

  return '<ul>' + items.join('') + '</ul>';
}
Comparison Operators & equal sign
  • Precedence ===and !==instead ==and!=
  • Use shortcuts
// bad
if (name !== '') {
  // ...stuff...
}

// good
if (name) {
  // ...stuff...
}

// bad
if (collection.length > 0) {
  // ...stuff...
}

// good
if (collection.length) {
  // ...stuff...
}
blank
  • Use two spaces as indentation
// bad
function () {
∙∙∙∙var name;
}

// bad
function () {
∙var name;
}

// good
function () {
∙∙var name;
}
  • Put a space before the curly braces
// bad
function test(){
  console.log('test');
}

// good
function test() {
  console.log('test');
}

// bad
dog.set('attr',{
  age: '1 year',
  breed: 'Bernese Mountain Dog'
});

// good
dog.set('attr', {
  age: '1 year',
  breed: 'Bernese Mountain Dog'
});
  • Spaces apart the operator
// bad
var x=y+5;

// good
var x = y + 5;

Above is the front-end architecture of the four core code in the core part of the next few articles will introduce three other core respectively, they are the processes, testing and documentation.

Links

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12072395.html