Web Front End Basics Summary

The first part.js

1. Js data type

  • Basic data types: Boolean, Number, String, undefined, Null, Symbol (new in ES6, representing unique values)

  • Reference data types: Object, Array, Function

2. Data type judgment

  • Typeof: Typeof returns a String representing the data type, including Number, Boolean, String, Symbol, Object, undefined, Function, etc., but cannot judge Null, Array, etc
  • Instanceof: instanceof is used to determine whether A is an instanceof B. The expression is: A instanceof B. Returns true if A is an instanceof B, and false otherwise. The instanceof operator tests whether an object has a constructor’s Prototype property in its prototype chain, but it cannot detect Null and undefined
  • Constructor: Constructor is very similar to instanceof. Unlike Instanceof, however, constructor can also handle detection of primitive data types. However, the constructor of the function is unstable, which is mainly reflected in the rewriting of the class prototype. In the process of rewriting, it is possible to overwrite the previous constructor, which results in inaccurate detection.
  • Object. The prototype. ToString. Call () : is the most commonly used the most accurate way.

Object.prototype.toString.call();               // [object String]

Object.prototype.toString.call(1);              // [object Number]

Object.prototype.toString.call(true);           // [object Boolean]

Object.prototype.toString.call(undefined);      // [object Undefined]

Object.prototype.toString.call(null);           // [object Null]

Object.prototype.toString.call(new Function()); // [object Function]

Object.prototype.toString.call(new Date());     // [object Date]

Object.prototype.toString.call([]);             // [object Array]

Object.prototype.toString.call(new RegExp());   // [object RegExp]

Object.prototype.toString.call(new Error());    // [object Error]

Copy the code

3. How to implement the call,apply, bind method?

In JS, every Function’s prototype points to a function.prototype object (JS is based on inheritance from the prototype chain). Therefore, every Function has apply, call, and bind methods, which inherit from Function. They all do the same thing, they both change the direction of this in the function.

  1. Method definition:
  • Apply: Calls a method on an object that replaces the current object with another. B. ply(A, arguments); The method that object A applies to object B.
  • Call: Calls a method on an object that replaces the current object with another. For example, b. call(A, args1,args2); That is, the method that object A calls object B.
  1. What are the similarities between call and apply?
  • The meaning of methods is the same, that is, the function of methods is the same;
  • The first parameter does the same thing;
  1. Differences between Call and apply:
  • They pass in different forms of lists
  • Call can pass in multiple arguments;
  • Apply can only pass in two arguments, so its second argument is usually passed in as an array
  1. Bind passes arguments in the same way as call, except that the apply and call methods execute immediately after the call. Bind returns a new function that does not execute immediately and needs to be executed manually.

  2. The meaning of existence:

  • Implement (multiple) inheritance

Function.prototype.myBind = function(content) {
    if(typeof this! ='function') {throw Error('not a function')}let _this = this;
    let args = [...arguments].slice(1) 
    let resFn=function(){
        return _this.apply(this instanceof resFn?this:content,args.concat(... arguments)) }return resFn
};
 
 /** * Each function can call the call method to change the this keyword currently executed by the function, and support passing in the argument */
Function.prototype.myCall=function(context=window){
      context.fn = this;// This refers to the function that calls myCall
      let args=[...arguments].slice(1);
      letresult=content.fn(... args)// Destroy this pointer
      delete context.fn;
      return result;
}
/** * The apply function passes in the this pointer and the parameter array */
Function.prototype.myApply = function(context=window) {
    context.fn = this;
    let result;
    if(arguments[1]){ result=context.fn(... arguments[1])}else{
        result=context.fn()
    }
    // Destroy this pointer
    delete context.fn;
    return result;
}


Copy the code

4. This refers to the problem

Due to the design principle of JS: in functions, you can reference variables in the runtime environment. Therefore, we need a mechanism that allows us to retrieve the current runtime environment from within the function body, and that is this. So to understand what this refers to, we really want to understand the environment in which the function is running, or in human terms, who called the function. The value of this is checked at execution time, not at definition. Because this is part of the execution context, the execution context needs to be determined before the code is executed, not when it is defined.

  • For calling foo directly, no matter where foo is placed, this must be window, right

  • For obj.foo(), we just need to remember that whoever called the function is this, so this in the foo function is the obj object in this scenario

  • In the constructor pattern, the occurrence of this. XXX = XXX in the class (in the function body) is an instance of the current class

  • Call, apply, and bind: this is the first argument

  • The arrow function this points to: the arrow function does not have its own this. If it does, this of the outer function is the this of the inner arrow function. If not, this is the window.

5. Prototype/constructor/instance

  • Prototype: A simple object used to implement object property inheritance. Can be simply understood as the father of the object. In Firefox and Chrome, each JavaScript object contains a __proto__ (nonstandard) attribute pointing to its parent (the object’s prototype), accessible from obj.__proto__.

  • Constructor: a function that creates an object using new.

  • Instance: Objects created through constructors and new are instances. Instances point to prototypes via __proto__ and to constructors via constructor.

6. The prototype chain

Concept: A prototype chain is made up of prototype objects. Each object has a proto attribute that points to the prototype of the constructor that created the object. Proto connects objects together to form a prototype chain. Is a finite chain of objects that implements inheritance and shared properties.

  • Attribute search mechanism: when searching for the attribute of an Object, if the instance Object itself does not exist, it will search up the prototype chain and output the attribute when it is found. If it does not exist, it will continue to search up the prototype chain until it reaches the top prototype Object. Prototype.

  • Attribute modification mechanism: only the attribute of the instance object itself will be modified. If it does not exist, the attribute will be added. If you need to modify the attribute of the prototype, you can use: b.prototype.x = 2; This, however, causes the properties of all instances that inherit from the object to change.

7. Inheritance (Prototype chain inheritance)

Concept: In JS, inheritance usually refers to prototype chain inheritance, that is, by specifying the prototype, and can inherit the properties or methods on the prototype through the prototype chain. The prototype chain is the most primitive pattern for implementing inheritance, which is implemented through the Prototype property. Use an instance of a parent class as a prototype for a subclass. There are six inheritance methods in common use:

  • Prototype chain inheritance
  • Borrow constructor inheritance
  • Combinatorial inheritance (combinatorial stereotype chain inheritance and borrowed constructor inheritance) (common)
  • Primary inheritance
  • Parasitic inheritance
  • Parasitic combinatorial inheritance (common)

8. Execution context (EC) and execution stack

  • Execution context: An abstraction of the context in which the current JavaScript code is parsed and executed. Any code that runs in JavaScript runs in the execution context. The life cycle of an execution context consists of three stages: create stage → execute stage → reclaim stage
  • Execution stack: The JavaScript engine creates an execution stack to manage the execution context. You can think of the execution stack as a stack structure for storing function calls, following the principle of first in, last out.

9. Scope and scope chain

  • Scope: The execution context also contains the scope chain. A scope can be understood as the variables declared in that context and the scope of the declaration. Can be divided into block-level scope and function scope (also can be understood as: scope is an independent site, so that variables do not leak out, exposed. In other words, the most useful use of a scope is to isolate variables. There is no conflict between variables with the same name in different domains.
  • Scope chain: A scope chain can be thought of as a list of objects, including the parent and its own variable objects, so we can access variables or functions declared in the parent through the scope chain. We know that we can access parent and even global variables in the execution context, thanks to scope chains.

10. Closure

Concept: A function defined inside a function. The inside function can access the variables of the outside function, and the outside variables are part of the inside function. Closures belong to a special class of scopes called static scopes. It can be defined as: when the parent function is destroyed, the returned child function still retains the > parent variable object and scope chain in the [[scope]], so can continue to access the parent variable object, such a function is called a closure.

  • 1. Use closures to access variables in functions. 2. Variables can be stored in memory for a long time, resulting in a long life cycle.
  • Disadvantages: Closures should not be abused as they can leak memory and affect web page performance.
  • Application scenario: 1. Functions are passed as parameters. 2. Function as return value

/** *JavaScript functions form closures. Closures are a combination of functions and the lexical environment in which they are declared. The environment contains any local variables that were in scope when the closure was created. * * /

function foo(){
  var num = 1
  function compute(){
    num++
    return num
  }
  return compute
}

var fn = foo()
fn()

The num variable and the compute function form a closure

Copy the code

11. Shallow and deep copies

Shallow copy:

A. Concept: Shallow copy copies only Pointers to an object, not the object itself. The old and new objects still share the same memory. The original object will also be affected.

B. methods:

  • Shallow copy is implemented using the = assignment operator.

  • Slice and concat are commonly used for shallow copies of arrays.

  • Array shallow copy – traversal.

  • Shallow copy of Object -object.assign ().

  • Object shallow copy – extension operator

Deep copy:

A. Concept: When data is copied, all reference structures of the data are copied. To put it simply, if two data structures are identical and independent in memory, the reference type is copied instead of just the reference relationship. The original object is no longer affected by the modification.

B. methods:

  • Leverage Parse and Stringify in JSON objects.
Parse (json.stringify (obj)) deep copy disadvantages: 1. Time becomes a string instead of a time object. 2. If obj contains function,undefined, then serialized result will lose function,undefined 3. If obj contains NaN,Infinity, and -infinity, then the serialized result will be null 4.json.stringify () can only serialize the object's enumerable property 5. If there are RegExp and Error objects in obj, the serialized result will be emptyCopy the code
  • Objects are recreated and assigned at each level using recursion.

For details on deep copy and shallow copy function encapsulation, please click here

12. Difference between require and import

Similarities:

  • Both import and require are modularized

Difference:

  • Require is a CommonJs syntax (introduced by the AMD specification), and CommonJs modules are objects; Import is an ES6 syntactically standard (not supported by browsers, essentially transcoding ES6 to ES5 using node Babel, import is transcoded to require). Es6 modules are not objects
  • Require is a method that loads the entire module (that is, all the methods in the module) at runtime, generates an object, and then reads it from the object (only the object is available at runtime, not static at compile time). In theory, it can be used anywhere in the code; Import is called at compile time to determine the dependency of module blocks, input variables (ES6 module is not an object, but the output code is specified by export command, and then the import input is used to load only the methods in import, other methods are not loaded), import has promotion effect. Export and import can be anywhere in the module, but must be at the top of the module. If they are in any other scope, an error will be reported. Es6 is designed to improve compiler efficiency, but not runtime loading
  • Require is an assignment process that assigns the result of require (object, number, function, etc.), an object of export by default, to a variable (copy or shallow copy); Import is the deconstruction process (who is needed, who is loaded)

Remark:

  • Require supports dynamic import, which is synchronous import and value copy. Changes in exported values do not affect imported values.
  • Import does not support dynamic import and is being proposed (supported under Babel). It is an asynchronous import and points to the memory address. The import value changes with the export value.

13. Commonjs and ES6 module differences

  • Commonjs is module. Exports, exports, require import; For ES6, export exports and import imports.
  • Commonjs is a runtime load module; ES6 determines module dependencies during static compilation.
  • ES6 pushes all imports to the top at compile time; Commonjs will not promote require.
  • Commonjs modules are copies; Es6 modules are references. Commonjs exports a copy of the value and caches the loaded result. If the value is changed internally, it will not be synchronized externally. ES6 is a reference to the export, and internal changes can be synchronized externally.
  • The implementation principle of cyclic import is different between the two. Commonjs is that when a module encounters cyclic load, it returns the value of the part that has been executed, rather than the value after all the code has been executed. The two may be different. So you have to be very careful when you enter variables; ES6 modules are dynamic references, and if you use import to load variables from a module (i.e., import foo from ‘foo’), those variables are not cached, but instead become a reference to the loaded module, requiring the developer to ensure that the value is actually retrieved.
  • The top-level this in CommonJS refers to the module itself; In ES6, the top layer of this points to undefined.

14. Anti-shake and throttling

The anti-shake and throttling function is one of the most commonly used high-frequency trigger optimization methods, which can greatly help performance.

  • Debounce: The optimization of multiple high-frequency operations to be performed only on the last time, usually in the case of user input, only one input verification is performed after the input is completed.

/** * Debounce optimizes multiple high-frequency operations to perform ** only on the last time@param {Function} Fn requires an anti-shake function *@param {Number} Number of milliseconds to wait *@param {Boolean} Immediate Optional, set to true, debounce will call this function * at the start of the wait interval@return {Function}* * /
 const debounce= (fn, wait, immediate) = >{
    let timer = null

    return function() {
        let args = arguments
        let context = this

        if(immediate && ! timer) { fn.apply(context, args) }if (timer) clearTimeout(timer)
        timer = setTimeout(() = > {
            fn.apply(context, args)
        }, wait)
    }
}

Copy the code
  • Throttling: To reduce the frequency and optimize high-frequency operations into low-frequency operations, you need to throttle the operation every 100 to 500 ms. The operation scenario is scrollbar or REsize events.

/** throttle optimizes high-frequency operations to low-frequency operations every 100 to 500 ms@param {Function} Fn requires an anti-shake function *@param {Number} Number of milliseconds to wait *@param {Boolean} Immediate Optional executes immediately. If this is set to true, debounce will call this function * at the start of the wait interval@return {Function}* * /
 const throttle =(fn, wait, immediate) = >{
    let timer = null
    let callNow = immediate
    
    return function() {
        let context = this,
            args = arguments

        if (callNow) {
            fn.apply(context, args)
            callNow = false
        }

        if(! timer) { timer =setTimeout(() = > {
                fn.apply(context, args)
                timer = null
            }, wait)
        }
    }
}

Copy the code

15. AST

Abstract Syntax Tree, which parses code letter by letter into Tree object form. This is the basis for translation between languages, code syntax checking, code style checking, code formatting, code highlighting, code error prompts, code auto-completion, and so on.

16. Compilation principle of Babel

Babel is a transpiler that feels more accurate than a compiler, called transpiler, because it simply translates higher-version rules of the same language into lower-version rules, unlike a compiler that outputs lower-level code in another language. Similar to the compiler, however, the Babel translation process is divided into three stages: parsing, transforming, and generating. Taking ES6 code translation as an example, the specific process of Babel translation is as follows:

  • Babylon parses the ES6/ES7 code into AST
  • Babel-traverse traverse the AST to get a new AST
  • The new AST is converted to ES5 via babel-Generator

It is also important to note that Babel only translates syntaxes introduced by new standards, such as ES6 arrow functions into ES5 functions; The new standard introduces new native objects, new prototype methods for some native objects, new apis (such as Proxy, Set, etc.) that Babel does not translate. Users need to introduce polyfill to solve the problem.

17. Coriolization of functions

The technique of filling in a function with several arguments and then returning a new function is called currization of the function. It is usually used to prespecify generic parameters for a function for multiple calls without intruding on the function.


const add = function add(x) {
	return function (y) {
		return x + y
	}
}

const add1 = add(1)

add1(2) = = =3
add1(20) = = =21

Copy the code

18. Common attributes and methods of ES6/ES7

Statement:

  • Let: Declare variables, block-level scope, no variable promotion, temporary dead zone, no repeated declarations allowed
  • Const: Declares a constant, read-only and cannot be modified

Deconstructing assignment:

  • Class/extend: Class declaration and inheritance
  • Set/Map: New data structure

Asynchronous solutions:

  • The use and implementation of Promise
  • Generator: yield: pause code; Next (): Continue executing the code

ES7 feature:

  • Array.prototype.includes() method that checks whether an Array contains a specified value, returning true if it does and false otherwise
  • Exponentiation operator (**), which is the same as math.pow (a, b)

//Array.prototype.includes()

['a'.'b'.'c'.'d'].includes('b')     // true

// Exponentiate operator (**)

3 ** 2            / / 9
// The same effect as:
Math.pow(3.2)   / / 9

Copy the code

19. Array Common operations

  • Map: Iterates through arrays of numbers, returning a new array of callback returns

  • ForEach: cannot break, can be stopped with a try/catch throw new Error

  • Filter: filter

  • Some: If one of the entries returns true, the whole is true

  • Every: One of the items returns false, the whole is false

  • Join: Generates a string by specifying a conjunction

  • Push/POP: Push and pop at the end, changing the array and returning the push/pop item

  • Unshift/shift: Head push and pop, change the array, return the action item

  • Sort (fn)/reverse: Sort and reverse, change the original array

  • Concat: concatenate array, does not affect the original array, shallow copy

  • Slice (start, end): Returns the truncated array without changing the original array

  • splice(start, number, value…) : returns an array of deleted elements, value being the insert item, changing the original array

  • IndexOf/lastIndexOf(value, fromIndex): Finds an array entry and returns the corresponding subscript

  • Reduce/reduceRight(fn(Prev, cur), defaultPrev): Execute in pairs, prev is the return value of the last reduction function, cur is the current value (starting from the second item)

  • Flat: [1,[2,3]] –> [1, 2,3]

20. Object Common operation methods

  • Keys (obj): Gets the traversable properties of the Object (keys)

  • Object.values(obj): Gets the traversable property value of an Object (value)

  • Object.entries(obj): Gets traversable key – value pairs of objects

  • Object.assign(targetObject,… Object): Merges traversable properties of objects

  • Object.is(value1,value2): Checks whether two values are the same

For more information, please click on js object methods

Part ii. Browser and server

1. The HTTP protocol

HTTP is short for Hyper Text Transfer Protocol. It is used to Transfer hypertext from the World Wide Web server to the local browser. HTTP is a TCP/ IP-based communication protocol to transfer data (HTML files, image files, query results, etc.). The object-oriented protocol, which belongs to the application layer, is suitable for distributed hypermedia information system because of its simple and fast way.

2. How HTTPS works

Asymmetric encryption and symmetric encryption are combined, asymmetric encryption algorithm is used to transfer the key for symmetric encryption algorithm, and then symmetric encryption algorithm is used for information transfer. It’s safe and efficient

3. Three handshakes

In THE TCP/IP protocol,TCP provides reliable connection services, using a three-way handshake to establish a connection:

  • First handshake: When establishing a connection, the client sends a SYN packet (SYN = J) to the server and enters the SYN_SEND state, waiting for confirmation from the server. SYN: Synchronize Sequence Numbers
  • Second handshake: After receiving a SYN packet, the server must acknowledge the client’s SYN (ACK = J +1) and send a SYN packet (ACK = K). In this case, the server enters the SYN_RECV state.
  • Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = K +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state to complete the three-way handshake. After completing the three-way handshake, the client and server begin transferring data

4. Enter the URL in the address bar of the browser and press Enter. The following process is performed

  • DNS resolution (the browser requests the DNS server to resolve the IP address corresponding to the domain name in the URL)
  • Establishing a TCP connection (three-way handshake)
  • Send request, analyze URL, set request message (header, body)
  • The server returns the requested file (HTML)
  • Release THE TCP connection (four waves)
  • Browsers render HTML text and display content

5. The difference between GET and POST requests

  • Get: cached, insecure, request length cannot exceed 4K, and will be saved in history
  • Post: no caching, secure, request data size unlimited, more encoding types

6. Common status codes

  • 1xx: Accept and continue processing
  • 200: Succeeded, and data is returned
  • 201: has been created
  • 202: have to accept
  • 203: Become, but not authorized
  • 204: Success, no content
  • 205: Succeeded. Reset the content
  • 206: Success, part of it
  • 301: Permanent move, redirect
  • 302: Temporary move, can use the original URI
  • 304: The resource is not modified and can be cached
  • 305: Proxy access is required
  • 400: Request syntax error
  • 401: Require identification
  • 403: Reject the request
  • 404: The resource does not exist
  • 500: Server error

7. Websocket

Concept: WebSocket is a protocol that HTML5 is beginning to provide for full-duplex communication over a single TCP connection. It is a persistent protocol, based on HTTP, that the server can actively push


new WebSocket(url)

ws.onerror = fn

ws.onclose = fn

ws.onopen = fn

ws.onmessage = fn

ws.send()

Copy the code

8. Web Worker

Web workers are JavaScript running in the background, independent of other scripts, and do not affect page performance. The multithreaded environment created by modern browsers for JavaScript. Some tasks can be created and assigned to worker threads for parallel running. The two threads can run independently without interference and communicate with each other through their own message mechanism.

/* Basic usage */
/ / create the worker
const worker = new Worker('work.js');

// Push messages to the main process
worker.postMessage('Hello World');

// Listen for messages from the main process
worker.onmessage = function (event) {
  console.log('Received message ' + event.data);
}

Copy the code

Limitations:

  • The same-origin restrictions
  • Document/window/alert/confirm cannot be used
  • Unable to load local resources

9. Promise

Concept: Promise is a solution to asynchronous programming that is more reasonable and powerful than traditional asynchronous solutions [callback functions] and [events]. It is now incorporated into the specification by ES6.

The common apis for Promise are as follows:

  • Promise.resolve(value) : Class method that returns a Promise object resolved with the value
  • Reject: class method, which differs only from resolve in that the Promise object returned has a state of Rejected.
  • Promise.prototype.then : Fn (vlaue){}, where value is the return result of the previous task. The function in then must return either a result or a new Promise object for subsequent THEN callbacks to receive.
  • Prototype. Catch: fn(err){}, err is an exception thrown by a callback before a catch is registered.
  • Promise.race: class method that executes multiple Promise tasks simultaneously and returns the result of the first completed Promise task executed, whether the Promise result succeeds or fails.
  • Promise.all: class method that executes multiple Promise tasks at the same time and returns the results of all Promise tasks as an array if all of them are successfully executed. If there is a Promise task Rejected, only the result of the Rejected task is returned.

// Basic usage
const promise = new Promise((resolve, reject) = > {
    try{
       resolve('success')}catch(err){
        reject('error')
    }
  
})

promise
  .then((res) = > {
    console.log('then: ', res)
  })
  .catch((err) = > {
    console.log('catch: ', err)
  })


Copy the code

10. How Ajax works

Simply put, it is the technique of making an asynchronous request to the server via an XmlHttpRequest object, getting data from the server, and then manipulating the DOM to update the page with javascript.


// Get request mode
function get(url, fn){
        var xhr=new XMLHttpRequest();
        xhr.open('GET', url, false);
        xhr.onreadystatechange=function(){
            if(xhr.readyState === 4) {if(xhr.status === 200){
                    fn.call(xhr.responseText);
                }
            }
        }
        xhr.send();
    }

// Post request mode
function post(url, data, fn){
        var xhr=new XMLHttpRequest();
        xhr.open('POST', url, false);
        // Add the HTTP header to the content encoding type when sending the message to the server
        xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
        xhr.onreadystatechange=function(){
            if (xhr.readyState === 4) {if (xhr.status === 200){
                    fn.call(xhr.responseText);
                }
            }
        }
        xhr.send(data);
    }

Copy the code

11. Cross domain

Concept: Cross-domain means that the browser cannot execute scripts from other sites. It is caused by the same origin policy (domain name, protocol, and port are all the same) of the browser, and is a security restriction imposed by the browser on JavaScript.

  • JSONP: Takes advantage of the fact that script tags are not cross-domain constrained, but only support GET requests.
  • Set CORS to access-Control-allow-origin: *
  • postMessage

/ / the json
function jsonp(url, jsonpCallback, success) {
  const script = document.createElement('script')
  script.src = url
  script.async = true
  script.type = 'text/javascript'
  window[jsonpCallback] = function(data) {
    success && success(data)
  }
  document.body.appendChild(script)
}


Copy the code

12. Browsers store cookies, LocalStorage, and SessionStorage

Cookies:

  • Generally, it is generated by the server. You can set the expiration time. If cookies are generated on the browser side, they are invalid after the browser is closed by default
  • The size is limited to about 4KB
  • This is carried each time in HTTP headers, and using cookies to store too much data can cause performance problems
  • Requires the programmer to encapsulate, the source Cookie interface is not friendly

LocalStorage:

  • It is stored permanently unless it is removed
  • As a general rule, be 5 MB
  • It is saved only in the client (browser) and does not communicate with the server
  • Native interfaces are acceptable and can be repackaged to provide better support for objects and arrays

SessionStorage:

  • This parameter is valid only in the current session and is cleared after you close the page or browser
  • As a general rule, be 5 MB
  • It is saved only in the client (browser) and does not communicate with the server
  • Native interfaces are acceptable and can be repackaged to provide better support for objects and arrays

13. Security

  • XSS attack: Inject malicious code. Cookie httpOnly; 2. Escape input and output on the page)
  • CSRF: Cross-site request forgery. 1. Get does not modify data; 2. Users’ cookies are not accessed by third-party websites; 3. Set a whitelist to prevent third-party websites from requesting it. 4. Request verification)

14. Memory leaks

  • Unexpected global variable: cannot be reclaimed
  • Timer: Not properly turned off, so referenced external variables cannot be released
  • Event listening: Not properly destroyed (may occur in earlier browsers)
  • Closures: Causes variables in the parent to be unable to be released
  • Dom references: When a DOM element is deleted, the reference in memory is not cleared correctly

15. Differences, advantages and disadvantages of single-page application (SPA) multi-page application (MPA)

Single page application (SPA) : In layman’s terms, a single page application, where the browser starts by loading all the necessary HTML, JS, and CSS. All page content is contained in this so-called home page. However, when writing, it is still written separately (page fragment), and then dynamically loaded by the routing program during interaction, single-page page jump, only refreshing local resources. It is mainly used on PCS.

Multi-page application (MPA) : An application has multiple pages. When switching to a page, the whole page is refreshed.

Advantages of single pages:

  • The user experience is good, fast, content changes do not need to reload the whole page, based on this point spa on the server less pressure.
  • Front and rear ends separated.
  • The effects of the page will be cool (such as a special animation when switching between pages).

Disadvantages of single page:

  • Bad for SEO.
  • Navigation is not available. If you must navigate, you need to implement forward and backward. (Since it is a single page and cannot use the browser’s forward and backward functions, you need to set up your own stack management).
  • The initial loading takes a lot of time.
  • Page complexity has increased considerably.

Part iii. Vue

1. The concept

Vue is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

Characteristics of 2.

  • Single page application
  • Two-way data binding: View changes automatically update data; Data update view changes automatically
  • Progressive: vue vue-router Indicates the route vuex axios
  • Framework: code that you write is called by the framework (library: code that calls the library yourself)
  • declarative

3. Vue2. X Responsive data Principle (data hijacking)

When Vue initializes data, it iterates over the data and converts these properties into getters/setters using Object.defineProperty. Each component instance has a Watcher instance, and when a page uses a property, the dependency collection is first performed with the getter (the watcher for the current component is collected). If the property changes, the setter is triggered to notify the dependency to update (publish subscribe).

Note:

  1. Object.defineproperty is a non-shim feature in ES5, which is why Vue does not support IE8 and earlier browsers.
  2. Due to JavaScript limitations, Vue cannot detect array and object changes.

4. Vue3. X Responsive data principle

Vue3. X uses Proxy instead of Object.defineProperty. Because proxies can listen directly for changes in objects and arrays, there are as many as 13 interception methods. And as a new standard, browser vendors will continue to focus on performance optimization.

5. Life cycle

  • BeforeCreate: is to be created. At this stage, after instance initialization, neither data observation nor event mechanism has been formed
  • “Created” : created. At this stage when the vUE instance is created, we also print the data and DOM elements.
  • Beforemount: To be mounted. In the last stage we know that the DOM has not been generated and the related attribute is still undefined, so this stage is about to mount.
  • Mounted: The rendering is complete. Mounted is the most commonly used function. It is where all asynchronous requests are placed. At this stage, both the data and the DOM are rendered.
  • BeforeUpdate: Rendering is about to be updated. Vue follows the data-driven DOM principle. When we modify the data of vUE instances, vUE automatically updates the view for us.
  • Updated: Updated after rendering. To not see the effect of the same – function in the fail phase, I comment out the beforeUpdate function, add the update function and bind the click event
  • BeforeDestroy: Before destruction. The previous vUE has successfully updated the DOM through data-driven updates. When we no longer need the VUE to manipulate the DOM, we need to destroy the VUE. That is, we need to remove the vUE instance’s association with the DOM and call destroy to destroy the current component. Before destruction, the beforeDestroy hook child function is triggered.
  • Destroyed: after destruction. After destruction, the Destroyed hook function is triggered.

6. Vue instructions

  • V-model: placed on form elements INPUT, Textarea, SELECT >option to implement two-way data binding
  • V-text: displays the corresponding text
  • V-once: The corresponding label is rendered only once
  • V-show: Indicates whether the command can be displayed
  • V-html: Renders the labels in the value
  • V-for: Loop to display elements
  • 14. v-bind: used to bind inline attributes
  • V-if: Controls whether to render the element
  • V-cloak: Need to work with CSS Use: Solve the mustache display problem
  • V-pre: Skip compilation of labels with this instruction and their children, and compile as native code

7. Event modifiers

  • .self fires only when the element itself is clicked
  • .stop Prevents bubbling events
  • . Prevent Prevents default events
  • .once The corresponding function fires only once
  • .capture fires a secondary binding event during the capture phase
  • .passive implements default events first (rolling behavior)

8. Form modifiers

  • . Number Is converted to a number, similar to parse
  • Trim Trim the whitespace before and after the string

9. Directives Are self-defined


// Register a global custom directive 'V-focus'
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus elements
    el.focus()
  }
})

// If you want to register local directives, a cache option is also accepted in the component
directives: {
  focus: {
    // The definition of a directive
    inserted: function (el) {
      el.focus()
    }
  }
}

// Then you can use the new V-focus attribute on any element in the template, as follows:

<input v-focus>

Copy the code

An instruction definition object can provide the following hook functions (all optional) :

  • Bind: Called only once, the first time a directive is bound to an element. This is where you can perform one-time initialization Settings.

  • Inserted: Called when the bound element is inserted into a parent (the parent is guaranteed to exist, but not necessarily inserted into the document).

  • Update: called when the component’s VNode is updated, but may occur before its child VNodes are updated. The value of the instruction may or may not have changed. However, you can ignore unnecessary template updates by comparing the values before and after the update (see below for detailed hook function parameters).

  • ComponentUpdated: Invoked when the VNode of the component where the directive resides and its child VNodes are all updated.

  • Unbind: Called only once, when an instruction is unbound from an element.

10. Vue-router Indicates route transmission parameters

Two parameter transmission modes are provided:

  • Query the ginseng (question mark participation) : route mapping table need not change: to = {path: “‘, query: {}} or: to = {name:” ‘, query: {}}

  • Params parameter passing (path parameter passing) : add /: to the mapping table as a variable; : to = {name: “‘, params: {variables: ‘}}}

11. In which lifecycle are interface requests generally placed?

Generally, interface requests are stored in Mounted. However, server rendering does not support Mounted, so you need to add it to created.

12. Computed is different from Watch

  • Computed in nature is a watcher with a cache that updates the view when dependent properties change. This method is applicable to computing scenarios where performance is consumed. When expressions are too complex, putting too much logic in a template can make the template difficult to maintain, and complex logic can be handled in computed properties.

  • Watch is not cacheable, but more of an observer, listening for certain data to perform callbacks. When we need to listen deeply for properties in an object, we can turn on the deep: True option, which will listen for each item in the object. This can cause performance problems and can be optimized by using string listening. If it is not written to the component, don’t forget to use unWatch to log out manually.

13. Difference between V-if and V-show

When the condition is not fixed, v-if does not render the DOM element. V-show does display, which switches the display and hiding of the current DOM.

14. Why is data a function?

When a component is reused multiple times, multiple instances are created. Essentially, these instances all use the same constructor. If data is an object, the object is a reference type that affects all instances. So to ensure that data does not conflict between different instances of the component, data must be a function.

15. Vue template compilation principle

To put it simply, Vue compilation is the process of converting a template into a render function. Will go through the following stages:

  • Generate an AST tree (parsing the template, generating an AST syntax tree (which describes the entire template as a JavaScript object))

  • To optimize the

  • codegen

16. Two implementation principles of routing

  • Hash mode: The Window object provides the onHashChange event to listen for changes in the Hash value, which is triggered whenever the Hash value in the URL changes.

  • History mode: PopState listens for changes in the History stack and rerenders when changes occur. Use the pushState method to add functionality. Replace functionality with replaceState

17. Keep – the alive

Keep-alive implements component caching and does not uninstall the current component when the component is switched. Two commonly used attributes include/exclude allow components to cache conditionally. Two life cycles, activated/deactivated, are used to determine whether the component is active. In keep-alive, LRU(Least Recently Used) algorithm is also Used.

What are the communication modes of Vue2. X components

  • Parent component communication: props, $ON ($off logout), $emit, $refs call properties or methods of child components by instance, Provide, inject, etc.

  • Sibling communication: EventBus and Vuex

  • Cross-level component communication: Vuex, $listeners, $listeners, Provide, etc.

19. SSR

Concept: SSR is server rendering, that is, Vue renders the tags into HTML on the client side and then returns the HTML directly to the client side.

Advantages:

  • SSR has better SEO
  • The first screen loads faster

Disadvantages:

  • Development conditions will be limited
  • Server-side rendering only supports two hooks, beforeCreate and Created, which need special processing when we need some external extension libraries. Server-side rendering applications also need to run in node.js environment.
  • There will be more load demands on the server.

20. Performance optimization

  • Coding phase
  1. Minimize the amount of data in data. Getter and setter are added to all data in data, and the corresponding Watcher is collected
  2. V-if and V-for cannot be used together
  3. Use the event broker if you need to use V-for to bind events to each element
  4. The SPA page uses the keep-alive cache component
  5. In more cases, use v-if instead of V-show
  6. Key guarantees uniqueness
  7. Use routing lazy load, asynchronous components
  8. Anti-shake and throttling
  9. Import third-party modules as required
  10. Long lists scroll to visual area for dynamic loading
  11. Lazy loading of images
  • SEO optimization
  1. pre-rendered
  2. Server rendering SSR
  • Packaging optimization
  1. The compression code
  2. Tree Shaking/Scope Hoisting
  3. Load third-party modules using CDN
  4. Multithreaded package Happypack
  5. SplitChunks removes public files
  6. SourceMap optimization
  • The user experience
  1. Skeleton screen
  2. PWA
  3. Client cache, server cache

21. Vuex

Concept: Vuex is a state management mode developed specifically for Vue applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

Structure:

  • State — Single State

  • Getters – Vuex allows us to define “getters” in stores (think of as computed properties of stores). Just like evaluating properties, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value changes.

  • Mutation — The only way to change the state in Vuex’s store is to commit Mutation. Each mutation has a string event type (type) and a callback function (handler). This callback is where we actually make the state change, and it accepts state as the first argument

  • Action — An Action commits mutation rather than a direct state change, and can contain any asynchronous operation.

  • Module — Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules — split the same way from top to bottom.

React

1. The concept

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. React allows you to combine short, independent pieces of code called “components” into complex UI interfaces.

2. Life cycle

  • ComponentWillMount: Called before rendering, both on the client side and on the server side.

  • ComponentDidMount: Called after the first rendering, only on the client side. The component then generates the corresponding DOM structure, which can be accessed through this.getDomNode (). If you want to use it with other JavaScript frameworks, you can use this method to call setTimeout, setInterval, or send AJAX requests (to prevent asynchronous operations from blocking the UI).

  • ComponentWillReceiveProps: component receives a new prop (updated) is invoked. This method is not called when render is initialized.

  • ShouldComponentUpdate: Returns a Boolean value. Called when the component receives new props or state. Not called during initialization or when forceUpdate is used. This can be used when you are sure that you do not need to update the component.

  • ComponentWillUpdate: Called when the component receives new props or state but has not yet rendered. Will not be called during initialization.

  • ComponentDidUpdate: Called immediately after the component has finished updating. Will not be called during initialization.

  • ComponentWillUnmount: Called immediately before the component is removed from the DOM.

React has proposed new changes to the life cycle:

  • Replace componentWillMount with getDerivedStateFromProps;
  • Replace componentWillUpdate with getSnapshotBeforeUpdate;
  • Avoid using componentWillReceiveProps;

The new recommended lifecycle is as follows:


class Component extends React.Component {
  / / replace ` componentWillReceiveProps `,
  // called during initialization and update
  // static function, cannot use this
  static getDerivedStateFromProps(nextProps, prevState) {}
  
  // Determine whether the component needs to be updated
  // Can be used for component performance tuning
  shouldComponentUpdate(nextProps, nextState) {}
  
  // Triggered when the component is mounted
  componentDidMount() {}
  
  / / replace componentWillUpdate
  // The latest DOM data can be obtained before the update
  getSnapshotBeforeUpdate() {}
  
  // called after component update
  componentDidUpdate() {}
  
  // The component is about to be destroyed
  componentWillUnmount() {}
  
  // The component is destroyed
  componentDidUnMount(){}}Copy the code

Usage suggestions:

  • Initialize state in constructor.

  • Listen for events in componentDidMount and unbind events in componentWillUnmount.

  • Requests for data are made in componentDidMount, not componentWillMount.

  • To update state based on props, use getDerivedStateFromProps(nextProps, prevState).

  • You can listen for props or state changes at componentDidUpdate.

  • When setState is used for componentDidUpdate, conditions must be added, otherwise an infinite loop will be entered.

  • GetSnapshotBeforeUpdate (prevProps, prevState) gets the latest render data before update, it is called after Render, before update.

  • shouldComponentUpdate: By default, every call to setState is bound to end up in the diff phase, but shouldComponentUpdate’s life hook returns false to prevent the execution of subsequent logic directly. This is usually used for conditional rendering to optimize the performance of rendering.

3. React Route parameters are transmitted


import queryString from 'query-string'
/ / way
this.props.history.push({
    pathname: '/course/platformCourse'.search: queryString.stringify({
         id: '0212'.name:'hello'})})2 / / way
this.props.history.push(`/cart? cartType=${cartType}`)

// Get the parameters and parse them
queryString.parse(this.props.location.search)

Copy the code

4. Output HTML methods directly


<div  dangerouslySetInnerHTML={{ __html: item.info}}></div>

Copy the code

5. HOC(High-level component)

Concept: A higher-order component is a function that takes a component as an argument and returns a new component. HOC is an advanced technique in React that reuses component logic. But higher-order components themselves are not a Replay API. It’s just a pattern, and that pattern is necessarily generated by the combinatorial nature of React itself.

Functions that can be achieved:

  • Combination of rendering
  • Conditions apply colours to a drawing
  • Operating props
  • Get refs
  • State management
  • The operating state
  • Rendering hijacked

Actual application scenarios of HOC in business:

  • Authority control, through the abstract logic, unified on the page authority judgment, according to different conditions for page rendering.

function withAdminAuth(WrappedComponent) {
    return class extends React.Component {
		constructor(props){
			super(props)
			this.state = {
		    	isAdmin: false,}}async componentWillMount() {
		    const currentRole = await getCurrentUserRole();
		    this.setState({
		        isAdmin: currentRole === 'Admin'}); }render() {
		    if (this.state.isAdmin) {
		        return <Comp {. this.props} / >;
		    } else {
		        return (<div>You do not have permission to view this page, please contact the administrator!</div>); }}}; }Copy the code
  • Performance monitoring wraps component life cycle for unified buried points.

function withTiming(Comp) {
    return class extends Comp {
        constructor(props) {
            super(props);
            this.start = Date.now();
            this.end = 0;
        }
        componentDidMount() {
            super.componentDidMount && super.componentDidMount();
            this.end = Date.now();
            console.log(`${WrappedComponent.name}Component rendering time isThe ${this.end - this.start} ms`);
        }
        render() {
            return super.render(); }}; }Copy the code
  • Code reuse, can be repeated logic for abstraction.

  • Dot log

  • Two-way binding

  • Form validation

Usage note:

  • Pure functions: Enhancement functions should be pure to avoid intruding into modifying meta-components.

  • Avoid usage contamination: Ideally, the extraneous parameters and events of the meta component should be passed through to keep usage unchanged as much as possible.

  • Namespaces: Add specific component names to HOC to make it easier to debug and find problems.

  • Reference passing: If you want to pass refs references to meta-components, use the react. forwardRef.

  • Static methods: Static methods on meta-components cannot be automatically exported, causing the business layer to be unable to call; Solution: function export and static method assignment.

6. Redux

Concept: Redux is a data management center that can be thought of as a global Data Store instance. It ensures the robustness, traceability and predictability of data through certain usage rules and restrictions. React is independent and can run independently in any JavaScript environment, thus providing a better data synchronization channel for homogeneous applications.

Core Concepts:

  • Single data source: The entire application has a unique state tree, where all states are ultimately maintained in a root Store.

  • State read-only: To ensure state control, it is best to monitor state changes. There are two requirements (the data in the Redux Store cannot be modified directly; Strictly control the execution of changes).

  • Pure functions: Specifies that changes can only be described by a pure function (Reducer).

Implementation method:

  • Store: A global Store singleton, with only one Store under each Redux application, which has the following methods to use:
  • GetState: getState;
  • Dispatch: Trigger action, update state;
  • Subscribe: Subscribe to data changes, register listeners;
  • Action: As a behavior carrier, it is used to map corresponding Reducer, and it can become the data carrier, transfer data from the application to the store, and it is the only data source of the store.

  • Reducer: a pure function that describes how to modify data. Actions belong to the behavior name and Reducer is the essence of the modification behavior.


/*store*/
/ / create
const store = createStore(Reducer, initStore)





/* Action*/

const action = {
	type: 'ADD_LIST'.item: 'list-item-1',}/ / use:
store.dispatch(action)

// Usually there is an Action creation function (Action creater) for ease of call.
funtion addList(item) {
	return const action = {
		type: 'ADD_LIST',
		item,
	}
}

// The call becomes:
dispatch(addList('list-item-1'))





/*Reducer*/
// @param {state}: old data
// @param {action}: Action object
// @returns {any}: new data
const initList = []
function ListReducer(state = initList, action) {
	switch (action.type) {
		case 'ADD_LIST':
			return state.concat([action.item])
			break
		defalut:
			return state
	}
}

Copy the code

Note:

  • Observe immutable data. Instead of modifying state directly, return a new object. Create a new object by assigning/copy/extend/deconstruct.
  • By default, the original data needs to be returned to avoid data clearing.
  • It is best to set the initial value to facilitate the initialization of the application and data stability.

Use react-redux with React:

  • Provider: Passes store into the component through context.

  • Connect: An advanced component that makes it easy to use Redux in React components.

  • Inject the component with props after filtering the store through mapStateToProps.

  • Create a method based on mapDispatchToProps that uses Dispatch to trigger the corresponding action when the component is invoked

  • Split and reconstruction of Reducer: As the project becomes larger, it will be difficult to maintain the Reducer if the Reducer of all states is written into one function; Reducer can be split, that is, function decomposition, and finally use combineReducers() to reconstruct and merge.

  • Asynchronous Actions: Because Reducer is a strict pure function, data requests cannot be made on Reducer. Data needs to be obtained first and then Action needs to be dispatched. The following are three different asynchronous implementation:

redex-thunk
redux-saga
redux-observable

Copy the code

Part five: Vue and React

1. Why does Vue update faster than React?

  • Vue (Reactive + dependency Collection) for reactive property updates, only the current component of the dependency collection will be updated precisely. Each component has its own rendering watcher, and does not recursively update its child components.
  • React updates recursively from top to bottom in a similar scenario. In other words, if there are ten nested child elements in the React ChildComponent, all levels are recursively rerender (without manual optimization), which is a performance disaster. (Hence React created Fiber and created asynchronous rendering, essentially making up for the performance they screwed up). Can they use this system of collecting dependencies? No, because they are Immutable by design and never modify properties on the original Object, a responsive dependency collection mechanism based on Object.defineProperty or Proxy would be useless (you always return a new Object, how do I know what part of the old Object you changed?). React recursively rerenders all subcomponents (except memo and shouldComponentUpdate), and then uses diff to determine which parts of the view to update. The recursive process is called reconciler, and it sounds cool, but the performance is catastrophic.

React and Vue virtual DOM differences

Similarities:

  • React and Vue use the same virtual DOM. Both use JS objects to simulate the real DOM, and then use the virtual DOM diff to minimize and update the real DOM. Although react and REACT have different dom update strategies, react uses a full top-down diff and VUE is a partial subscription model. But this has nothing to do with the virtual DOM

Difference:

  • Vue tracks the dependencies of each component without having to re-render the entire component tree; React requires shouldComponentUpdate to render components whenever the state of the application changes.

3. Similarities and differences between HOC and Mixin

Function:

  • Both Mixin and HOC can be used to solve the React code reuse problem

Mixin:

  • Mixins can be interdependent and coupled to each other, which is not conducive to code maintenance

  • Methods in different mixins can conflict with each other

  • There are so many mixins that components can sense and even deal with them, which can snowball in code complexity

HOC:

  • A higher-order component is a pure function with no side effects; the higher-order components do not depend on each other for coupling

  • Higher-order components can also cause conflicts, but we can avoid these behaviors by following conventions

  • Higher-order components don’t care how or why the data is used, and wrapped components don’t care where the data comes from. The addition of higher-order components does not burden the original components

4. What are the advantages of Hook

  • Reduce the risk of state logic reuse

Hooks and mixins have some similarities in usage, but the logic and state introduced by mixins can overwrite each other, and multiple hooks do not affect each other, so we do not need to focus part of our efforts on preventing conflicts that avoid logic reuse. Using HOC without conforming to the convention can also cause some conflicts, such as props overwrite, etc., while using Hook can avoid these problems.

  • Avoid hell of nesting

Heavy use of HOC made our code very deeply nested. Using Hook, we can achieve flat reuse of state logic without heavy component nesting.

  • Make components easier to understand

As we build our programs using class components, they each have their own state, and the complexity of business logic makes these components bigger and bigger, with more and more logic called in each lifecycle and harder to maintain. Using hooks allows you to extract more common logic and split a component into smaller functions, rather than forcing > split based on lifecycle methods.

  • Use functions instead of classes

Writing a class may require more knowledge than writing a function, with more points to watch out for, such as this pointing, binding events, and so on. In addition, computers can understand a class faster than they can understand a function. Hooks allow you to use more of React’s new features outside of classes.

Part vi. Webpack

1. What is webpack and how is it different from Grunt and Gulp

Concept:

  • Webpack is a module packaging tool. In Webpack, all modules are converted files by loader, injected hooks by plugin, and finally output files composed of multiple modules.
  • Gulp/Grunt is a build tool that optimizes the front-end development process

Similarities:

  • Grunt and Gulp were popular in the early days. Webpack is relatively mainstream now, but Gulp is still used for some lightweight tasks, such as packaging CSS files separately.

Difference:

  • Grunt and Gulp are based on tasks and streams (tasks, streams). Similar to jQuery, find a file (or a class of files) and do a series of chain operations on it to update the data on the stream. The chain operations constitute a single task, and multiple tasks constitute the entire Web build process.
  • Webpack is portal based. Webpack will automatically recursively parse all the resource files that need to be loaded by the entry, then use different loaders to process different files, and use Plugin to extend Webpack functionality.

2. Advantages and disadvantages of Webpack

Advantages:

  • Focus on dealing with modular projects, can do out of the box, one step in place
  • Plugin can be extended, convenient and flexible
  • The community is large and active, and new features are often introduced
  • Good development experience

Disadvantages:

  • Only for projects with modular development

3. Webpack construction process

The running flow of Webpack is a sequential process, from start to finish:

  • 1. Initialization parameters: Read and merge parameters from configuration files and Shell statements to obtain the final parameters

  • 2. Start compiling: Initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the object’s run method to start compiling

  • 3. Determine the entry: Locate all entry files based on the entry in the configuration

  • 4. Module compilation: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have gone through this step

  • 5. Complete module compilation: After using Loader to translate all modules in step 4, the final content of each module after translation and the dependencies between them are obtained

  • 6. Output resources: Assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content

  • 7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the output content to the file system

In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute a specific logic after listening for the event of interest, and the plug-in can call the API provided by Webpack to change the running result of Webpack.

4. What is entry,output

  • The entry entry tells WebPack which module to use as the starting point for building the project./ SRC /index.js by default

  • The output export, which tells WebPack where to output its packaged code and how to name it, defaults to./dist

5. What are bundles, chunks, and modules

  • Bundle: Files packaged by Webpack

  • Chunk: a chunk is a code block. A chunk is composed of multiple modules for merging and splitting codes

  • Module: is a single module under development. Each module corresponds to a file. Webpack will recursively find all dependent modules from the configured entry

6. What is loader and what is plugin, the difference between them

Concept:

  • Loader: module converter. Used to convert the original content of the module into new content as required. By using different loaders, Webpack can convert different files into JS files, such as CSS, ES6/7, JSX, etc

  • Plugin: Extension plug-in. Inject extension logic at specific points in the Webpack build process to change the build result or do what you want. A plug-in is an object that contains the Apply method, which participates in the entire Webpack process

Different:

  • Loader enables WebPack to load and parse non-JS files

  • Plugin can extend the functionality of WebPack to make it more flexible. You can change the output during the build through the Webpack API

Loader is used to convert the source code of modules, while plugin is designed to solve other things that loader cannot do, because plugin can be called at any stage to further process loader output across loaders

7. What are the common plugins and loaders and what are their functions

plugin:

  • Html-webpack-plugin is an external resource introduced in HTML files that can generate and create HTML entry files
  • Mini-css-extract-plugin Separates CSS files
  • Clean-webpack-plugin removes packaged files
  • HotModuleReplacementPlugin hot update application
  • Copy-webpack-plugin copies static files
  • Define-plugin: Defines environment variables
  • Commons-chunk-plugin: Extract common code
  • The Terser-webpack-Plugin compresses ES6 code through the TerserPlugin

loader:

  • File-loader: Outputs files to a folder, referencing the output file with a relative URL in the code
  • Url-loader: similar to file-loader, but can inject the contents of files into code base64 if the files are too small
  • Source-map-loader: Loads additional source map files to facilitate breakpoint debugging
  • Image-loader: loads and compresses image files
  • Babel-loader: Convert ES6 to ES5
  • Css-loader: loads the CSS and supports features such as modularization, compression, and file import
  • Style-loader: Inserts CSS code into JavaScript and loads CSS via DOM manipulation.
  • Eslint-loader: Checks JavaScript code through ESLint

8. What is module hot update

Hot updates to Webpack are also known as Hot Module Replacement, or HMR. This mechanism allows you to replace the old module with the new one without refreshing the browser. The hot property in devServer can be used for hot replacement of space-time modules.


// Through the configuration file
const webpack = require('webpack');
const path = require('path');
let env = process.env.NODE_ENV == "development" ? "development" : "production";
const config = {
    mode: env,
    devServer: {
        hot:true}}plugins: [
        new webpack.HotModuleReplacementPlugin(), // Hot loading plug-ins].module.exports = config;

Copy the code

9. What is the difference between webpack-dev-server and HTTP servers such as Nginx

Webpack-dev-server uses memory to store packaged files in the WebPack development environment. It can also use module hot update, which is simpler and more efficient for development than traditional HTTP services.

10. How to optimize long cache in Webpack

When the user visits the page, the browser will store the static resources accessed by the user to speed up the loading speed. However, every code upgrade or update requires the browser to download new code. The simplest and most convenient way is to introduce a new file name. In Webpack, you can specify chunkhash in output and separate frequently updated code from framework code. Use NameModulesPlugin or HashedModuleIdsPlugin to keep the repackaging file name unchanged.

11. How does Webpack deploy single-page and multi-page applications


    // Single page
    module.exports = {
        entry: './path/to/my/entry/file.js'
    }
    // Multi-page applications
    module.entrys = {
        entry: {
            pageOne: './src/pageOne/index.js'.pageTwo: './src/pageTwo/index.js'}}Copy the code

12. How to speed up Webpack construction

  • In multi-entry cases, the CommonsChunkPlugin is used to extract common code

  • Use the externals configuration to extract common libraries

  • The precompiled resource module uses the DllPlugin to precompile NPM packages that we reference but never modify, and then loads the precompiled modules in via the DllReferencePlugin.

  • Use Happypack to achieve multi-threaded accelerated compilation

  • Use Webpack-Uglify-Parallel to increase the compression speed of uglifyPlugin. In principle, Webpack-Ugli-fi – Parallel uses multi-core parallel compression to improve compression speed

  • Use tree-shaking and Scope compensation to weed out redundant code

13. How to leverage Webpack to optimize front-end performance (improve performance and experience)

  • Compress the code. Remove unnecessary code, comments, simplify code writing, and so on. Webpack UglifyJsPlugin and ParallelUglifyPlugin can be used to compress JS files, using CSSNano (CSS-loader? Minimize to compress CSS

  • CDN acceleration. During the build process, the referenced static resource path is changed to the corresponding path on the CDN. The resource path can be modified using the Webpack for the output parameter and the publicPath parameter of each loader

  • Removing dead code (Tree Shaking) Remove pieces of code that never go anywhere. This can be done by appending the parameter optimize-minimize when starting the Webpack

  • Extract common code

14. What are the changes to Webpack4

  • Mode /–mode parameter, added mode/–mode parameter to indicate whether development/production. Production focuses on packaged file sizes and development focuses on Goujiansud

  • To remove loaders, you must use rules (loaders and rules co-exist in version 3 but only rules are allowed in version 4)

  • Removed CommonsChunkPlugin (to extract the common code), with optimization. The splitChunks and optimization runtimeChunk instead

  • Supports es6 mode to import JSON files, and can filter useless code


let jsonData = require('./data.json')
import jsonData from './data.json'
import { first } from './data.json' // Only type in the first related items when packing

Copy the code
  • Update the Happypack plugin (happypack can do multi-threaded accelerated packaging)

  • ExtractTextWebpackPlugin adjustment, recommended to choose the new CSS file extraction KIII plug-in mini-CSS – extract-Plugin, production mode, increase minimizer

Part 7. HTML && CSS

1. Front-end Basic Interview questions (HTML+CSS section)

Front-end based interview (HTML + CSS) : zhuanlan.zhihu.com/p/28415923

2. 10 frequently asked questions about CSS in web front-end interview

Do you know the 10 frequently asked questions about CSS? : cloud.tencent.com/developer/a…

2. 3. Smart refrigerator

2019 CSS Classic Interview questions : blog.csdn.net/weixin_3369…

conclusion

All of the above are personal references and summaries from other blogs. My Github blog address please visit: Github blog

Reference to the post

  • Senior front-end factory interview secrets, escort for you jin SAN Silver four, direct dachang (on) – nuggets
  • Middle and senior front end big factory interview tips, winter for you to escort, direct dachang (middle) – React chapter
  • JavaScript interview 20 core test points
  • React to interview questions (on)