preface
Roll out person: Zi Yi (Ali Nailing Team)
Name: Programmer’s thought
Class: Nuggets
Grade: grade 3 in front
Bosses son implement the interview guide is meant to help everyone literacy, let everybody to understand some may have no contact with or things they don’t know, here is actually the most subject in deepening communication in the context of the produce, also does not affect the judgment about the interviewer interview, pure belong to the surface of the surface of the feel good, Think he can answer to come up and give extra points a question, is not the meaning that everybody understands make people difficult.
Due to the article word limit, many questions can not be detailed and in-depth answer (pure is lazy, just want to rush out the article one night, hey!) “I’m just sketching it out, and nonstandard answers, like asking a browser about the URL request process, will keep your interviewer talking for at least a few hours. Some questions are not questions or more general, it is not easy to answer, just skip, we see just for fun, don’t take it seriously. Nonstandard answer,
You are welcome to leave comments and accept any criticism and suggestions
The title
1. What types of computer storage devices do you know?
A:
- Random access memory
SRAM (SRAM, RDRAM, CDRAM, etc.)
- Read-only memory ROM
MROM, PROM, EPROM, EEPROM
2. In which device of the computer is the general code stored? How does the code run in the CPU?
A: 1) Before volatile execution, our code was mainly stored in memory. (2) THE CPU reads the data in the memory and put it in the register, and the data in the register is written into the memory and carried out four operations and relevant instructions in order. In this process, the register is mainly used to store the calculation data, and the arithmetic is responsible for the operation of the data in the register.
3. What are instructions and instruction sets?
A: Instructions generally refer to machine instructions, which are commands that can be executed by a computer to complete an independent computation logic. The set of all the instructions of a conventional computer is the instruction set of the computer.
4. How does JavaScript work? What is the difference between interpreted and compiled languages?
A: (1) JS code -> parse into AST -> generate bytecode (V8)-> generate machine code (compiler)
② Many sources will say that JavaScript, Python, and Ruby are “interpreted languages”, which are implemented through an interpreter. This is misleading: languages typically define their abstract semantics, not impose an implementation.
For example, C is generally considered a “compiled language,” but interpreters for C do exist, such as Ch. Similarly, C++ also has an interpreter version of the implementation, such as Cint.
What is commonly referred to as an “interpreted language” is a language that is primarily implemented as an interpreter, but that does not mean it cannot be compiled. Scheme, for example, which is often considered an “interpreted language,” has several compiler implementations. One of the first to support much of the R6RS specification was Ikarus, which allows Scheme to be compiled on x86. Instead of generating some kind of virtual machine bytecode, it ends up generating x86 machine code directly.
The interpreter is a black box. The input is the source code, and the output is the execution result of the input program. There is no separate “compile” step for the user. It’s very abstract, and it doesn’t matter how it’s done internally, as long as it’s done semantically. You can write a C interpreter that simply compiles the source code to an in-memory image using a normal C compiler, and then calls that image directly to get the result. The user takes it and finds that entering the source code directly can get the corresponding results of the source program, regardless of what is in the “black box” of the interpreter.
In fact, many interpreters are internally implemented in a “compiler + virtual machine” way, where the compiler converts the source code into AST or bytecode, and the virtual machine performs the actual execution. An “interpreted language” doesn’t mean that you don’t need to compile, just that you don’t need the user to explicitly use the compiler to get executable code.
That’s a lot of nonsense. I’m sure some gold digger will come after me. My point is that a language is truly an “interpreted language” if its dominant implementation is an interpreter, and its internal implementation is a compiler + virtual machine, and the virtual machine is interpreted, or its internal implementation is a compiler + tree traversal interpreter. If the internal virtual machine is implemented in a compiled way, it is actually quite different from the common impression of “interpreter”.
An example is ActionScript 3, which is generally considered an “interpreted language,” right? But does this view view FlashPlayer as a whole as an interpreter and therefore AS3 as an “interpreted language” “” “? Or is AS3 an interpreted language because the virtual machine in FlashPlayer uses interpreted execution?
5. How to compile Babel?
A: First, Babel’s function is to go from one source to another, acting as a conversion compiler, which can be briefly described as parse (parse JS code) -> transform (parse and modify AST) -> rebuild (convert modified AST to another JS code)
6. How are arrays and functions in JavaScript stored in memory?
Answer: ① array, JS array is mainly in the form of continuous memory storage of FixedArray, HashTable in the form of HashTable storage.
② Function, function belongs to the reference data type, stored in the heap, in the stack memory only saves an address to represent the heap memory reference. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heap.
7. What’s the difference between event loops in browsers and Node.js?
A: (1) Event loop in the browser: Macrotasks:
Script (overall code)
setTimeout
setInterval
setImmediate
I/O
UI rendering
event listner
Microtasks:
process.nextTick
Promises
Object.observe
MutationObserver
In the browser, every time a listener event occurs, the related tasks bound to the event listener are added to the callback queue. Tasks generated by events are asynchronous tasks. Common event tasks include:
- Event tasks generated by user interaction events, such as input operations;
- Event tasks generated by timers, such as setTimeout;
- Event tasks generated by asynchronous requests, such as HTTP requests.
When the main thread is running, it generates a heap and a stack, where the heap is memory and the stack is function call stack. As you can see, the Event Loop is responsible for executing code, collecting and processing events, and executing subtasks in the queue, which includes the following procedures.
- JavaScript has a main thread and a call stack, and all tasks will eventually be placed on the call stack for the main thread to execute.
- The synchronization tasks are placed on the call stack and wait for the main thread to execute in sequence.
- There is a callback queue outside the main thread, and the asynchronous tasks in the callback queue will eventually run as a call stack inside the main thread.
- Synchronous tasks are executed on the main thread, and the stack code calls the browser API as it executes, resulting in asynchronous tasks.
- The asynchronous task puts the asynchronous task and its associated callback function in the callback queue when it has a result (such as when the event being listened to occurs).
- After the task in the call stack is finished, the main thread is idle and will get the task from the callback queue for processing.
- This process is repeated over and over again. This is what JavaScript does, called an Event Loop.
Event loop in NodeJs:
- Timersj phase: This phase performs the callback for timer (setTimeout, setInterval)
- I/O callbacks: Performs system call errors, such as network communication error callbacks
- Idle,prepare: Used only in node
- Poll: Gets a new I/O event, where the node blocks when appropriate
- Check: Perform a callback to setImmediate()
- Close callbacks: Perform a callback to the socket’s close event
(3) Differences: In the browser environment, the task queue of microtask is executed after each macrotask is executed. In Node.js, microTasks are executed between the stages of the event loop. When a phase is completed, the tasks in the MicroTask queue are executed. If the Node11 version performs a macro task in a phase (setTimeout,setInterval, and setImmediate), the microtask queue is executed instantaneously, just as it does on the browser side.
setTimeout(() = >{
console.log('timer1')
Promise.resolve().then(function() {
console.log('promise1')})},0)
setTimeout(() = >{
console.log('timer2')
Promise.resolve().then(function() {
console.log('promise2')})},0)
// Browser environment:
timer1=>promise1= >timer2= >promise2
// Node after V11
timer1=>promise1= >timer2= >promise2
// Node 10 and earlier
timer1=>promise1= >timer2= >Timer1 => < span style = "word-break: break-all;timer2= >promise1= >(If the second timer is already in the completion queue)Copy the code
8. What are the advantages of ES6 Modules over CommonJS?
A:
- Both CommonJS and ES6 Modules can assign values to imported objects, that is, change the values of the internal properties of the object;
- The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value. The ES6 Module is read-only and cannot be changed. Specifically, the pointer cannot be changed.
- The CommonJS module is a runtime load, and the ES6 module is a compile-time output interface.
- The require() of the CommonJS module loads the module synchronously, and the import command of the ES6 module loads asynchronously, with a separate module dependency resolution phase.
- The import interface is read-only and cannot be modified. You cannot change the pointer to the variable, but you can change the pointer to the variable. You can reassign commonJS (change the pointer to), but assignment to ES6 Module will compile error.
Advantage: CommonJS loads an object (the module.exports property) that is generated only after the script has run. While ES6 Modules are not objects, its external interface is just a static definition, which is generated during the static code parsing phase.
9. How is a high-level programming language compiled into machine language?
A: High level language code -> parsing into AST (accompanied by lexical analysis, parsing)-> Generating bytecode (V8)-> Generating machine code (compiler)
10. What are the stages of a compiler? At what stage is data type checking generally performed?
A: The compiler generally works in four phases:
-
Parse phase: the V8 engine is responsible for converting JS code into an AST (abstract syntax tree).
-
Ignition phase: The interpreter converts the AST into bytecode, and parsing and executing the bytecode provides the information needed to optimize the next phase of compilation.
-
The TurboFan phase: The compiler optimizes the bytecode into executable machine code using information gathered in the previous phase;
-
Orinoco phase: Garbage collection phase in which memory space no longer used in the program is reclaimed.
Data type checking is typically done before the Parse phase, because parsing is performed to extract the structure of the sentence before the AST is generated. Broadly speaking, the input is usually the source code of the program, and the output is usually the syntax tree (also called parse Tree, etc.) or abstract syntax tree (AST). Further down the line, there are generally scanners (tokenizer or lexical analyzer) and parsers (syntax Analyzer) in the broad sense. The input to the scanner is typically text, which has been lexically analyzed, and the output is a stream of words that have been cut into them. The narrow parser input is a stream of words, and the output is either a syntax tree or a condensed AST after parsing.
11. What is the role of the virtual machine during compilation?
A: Virtual machine (VM), the meaning of which is to implement the semantics of high-level languages. Since VM is called “machine”, it is generally considered that the input is the instruction sequence that satisfies some instruction set architecture (ISA), the intermediate transformation is the instruction sequence of target ISA and executed, and the output is the execution result of the program, which is VM. The source and target ISA can be of the same type, this is the so-called same-ISA VM. The virtual machine doesn’t magically execute code, it has to implement the semantics of the input program in some way, and there are also several options: “compile”, such as Microsoft’s. NET CLR; “Explain” such as CPython, CRuby 1.9, many older JavaScript engines, etc. There are also hybrids in between, such as Sun’s JVM, HotSpot. If compiled, the VM converts the input instructions into a form that can be executed directly by the underlying system (typically native code), and then executes them. If interpreted, the VM executes the input instructions one at a time.
12. What is an intermediate code (IR) and what does it do?
A: IR is intermediate code generated by LLVM to optimize the compiler or VM so that the optimized machine code executes more efficiently, while avoiding the need to cache compiled binary code that takes up more memory.
13. What is cross-compilation?
A: Generating executable code on one platform for another.
14. What is the difference between publish/subscribe and observer?
A: In observer mode, the observed usually maintains a list of observers. The observer is notified when the state of the observed changes.
In publish-subscribe mode, a specific publisher dynamically maintains a list of subscribers: event notifications that can be published to the corresponding subscribers can be started or stopped at run time as the program needs them.
The difference is that the publisher itself does not maintain a subscription list (it does not actively maintain a list like an observer), it delegates the work to the specific publisher (equivalent to the secretary, anyone who wants to know about me, just ask my secretary); When a subscriber receives a message from a publisher, it assigns specific subscribers to do the related processing.
15. When is the decorator pattern used?
A: The decorator pattern generally allows you to dynamically add new functionality to an existing object without changing its structure, essentially wrapping an existing object around it.
Use a lot of scenarios, such as writing jQ projects before, you can quickly and dynamically expand the methods above jQ, or vUE custom instructions, mainly hope to extend the old function through inheritance.
16. Describe your understanding of code decoupling design for large projects? What is Ioc? What design patterns are used to implement DI in general?
A: (1) Code decoupling, be sure to divide the code into modules rather than functions
-
The life cycle (initialization, destruction) of each module is managed uniformly by the framework: registration and destruction of related resources are managed uniformly by providing the universal class Disposable.
-
Modules do not directly introduce and invoke, but through the declaration of dependencies, from the framework to obtain the corresponding services and use.
-
Do not use global events directly for communication, but through subscription to specific services to handle: register the event and subscribe to the event in the same way this._register(), the processing of event-related resources is mounted to the Dispose () method
③ Code development should be componentized as soon as possible to improve reusability and avoid excessive coupling of business logic, which makes it difficult to expand
Ioc refers to dependency injection, simply understood as the decoupling of objects with dependencies by means of a “third party”. The proxy pattern is generally used.
17. List the programming paradigms you know?
A: declarative, imperative, and functional
18. What is Aspect Oriented (AOP) programming?
A: Aspect oriented programming is just a way of object-oriented programming. The dynamic embedding of other code during code execution is called aspect oriented programming.
What is functional programming? What is responsive programming? What is functional responsive programming?
A: Functional programming is a mathematically oriented abstraction concerned with mapping between data (algebraic structures). Functional programming describes computation as an expression evaluation.
Responsive programming is a declarative programming paradigm based on data flow and change passing.
Functional responsive programming is a hybrid, responsive programming ideas for the body, functional programming ideas for use.
20. How to achieve a top, middle and bottom three-row layout with a minimum height of 100px at the top and bottom and an adaptive middle?
A:
<div class="layout">
<div class="top">top</div>
<div class="content">content</div>
<div class="bottom">bottom</div>
</div>
Copy the code
html.body {
padding: 0;
margin: 0;
height: 100%;
/* Define the overall page height to 100%, important */
}
.layout {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.top {
height: 100px;
background: red;
}
.content {
flex: 1;
background: yellow;
}
.bottom {
height: 100px;
background: blue;
}
Copy the code
21. How to tell if an element is out of style and can optionally add a title or a Tooltip?
If the scrollHeight is greater than the clientHeight attribute, the element can scroll vertically. If the scrollHeight is greater than the clientHeight attribute, the element can scroll vertically. If horizontal scrolling is detected, use scrollWidth and clientWidth.
22. How to automatically overflow the left side of CSS elements (… Overflow on the left)?
Answer: the left width automatically grows, the right width automatically grows and cannot overflow. When the length of the left text exceeds, the left text overflows. CSS has a direction property that sets the text direction from right to left: direction: RTL
/* css */
.footer {
width: 300px;
height: 20px;
display: flex;
overflow: hidden;
}
.left {
background: #3cc8b4;
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 50px;
}
.right {
background: #9bc;
max-width: 250px;
}
.right-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Copy the code
/* html */
<div class="footer">
<div class="left">
leftleftleftleftleftleftleftleftleftleftleftleftleft
</div>
<div class="right">
<div class="right-ellipsis">
rightrightrightrightrightrightrightrightright
</div>
</div>
</div>
Copy the code
23. What is a sandbox? What does the browser sandbox do?
A: The purpose of the sandbox design is to allow untrusted code to run in an environment that limits its access to resources outside the quarantine zone.
24. How to solve the problem of automatically filling the password of a single table in the browser?
A: If the input type in the form is password, the password stored in the browser will be automatically filled in when you open the browser. To solve this problem, add autoComplete =”new-password” in the input. The reason why new-password can resolve off invalidation is that the only valid values for autoComplete are on and off. The default value is ON. If the autoComplete property has a value other than on and off, it will be invalid and the browser will abandon the execution of the property.
<input type="password" name="password" placeholder="Please enter your password" autocomplete="new-password"/>
Copy the code
25. What are the differences between Hash and History routes?
A: The hash routing mode is implemented based on the following features:
- The hash value in the URL is only a state of the client. That is, when a request is sent to the server, the hash part is not sent.
- Each change in the hash value adds a record to the browser’s access history. So we can use the browser’s back and forward buttons to control the hash switching;
- You can use the a tag and set the href attribute. When the user clicks the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash and change the HASH value of the URL.
- We can use the HashChange event to listen for the hash value to jump (render) to the page.
The implementation of the History routing pattern is based on the following features:
- The pushState and repalceState apis operate to implement URL changes;
- We can use popState events to listen for url changes and jump to the page (rendering).
- History.pushstate () or history.replacestate () do not trigger popState events, so we need to manually trigger the page jump (render).
26. Can we push a const array in JavaScript? Why is that?
A: Yes, or splice().
The const declaration creates a read-only reference to a value. This does not mean that the value it holds is immutable, just that variable identifiers cannot be reassigned. For example, in the case of references that are objects, this means that the contents of the object (for example, its parameters) can be changed.
27. What are the property descriptors of objects in JavaScript? What do they do?
A:
- The information is freely Configurable and works without additional control.
Configurability determines whether the property can be deleted using delete and whether the properties of the property descriptor can be modified. The default value is true
- Enumerable
Enumerability determines whether the property appears in an object’s property enumeration, such as whether it can be returned through a for-in loop. The default value is true
- Writable(Writable)
Writability determines whether the value of the property can be modified. The default value is true
- Value(attribute Value)
The property value contains the data value of the property. When the property value is read, it is read from this position. When a property value is written, the new value is stored in this location. The default value is undefined
- getter
The function called when the property is read. The default value is undefined
- setter
The function that is called when a property is written. The default value is undefined
28. What are the apis for Console in JavaScript?
A: I only used console.clear(), console.log(), console.info(), console.warn(), console.error(), console.time(), and console.timeend (). I don’t know anything else. I don’t use it very often
29. Compare the advantages and disadvantages of several asynchronous apis, such as Callback, Promise, Generator and Async.
A: First of all, callback is not an asynchronous API, it is a means of implementing JS asynchronous programming in the early years.
Promise is a community solution to the problem of callback hell in the ES6 release;
Generator is also an asynchronous programming solution. Its biggest feature is that it can give up the execution power of functions. Generator functions can be seen as containers for asynchronous tasks.
Async/await is a new asynchronous solution proposed in ES7. Async is the syntactic sugar for Generator functions. The advantage of Async/await is that the code is clear (unlike when you use promises, you need to write a lot of then method chains). Async /await is not only a way to program javascript asynchronously, but it is also nearly as readable as synchronized code, making it easier to understand.
30. What are the parameters of Object. DefineProperty? What does each of them do?
DefineProperty (Object, propertyname, descriptor)
- The object must be. The object on which to add or modify properties. This could be a native JavaScript object (that is, a user-defined or built-in object) or a DOM object.
- Propertyname required. A string containing the property name.
- Descriptor required. Property descriptors. It can be for data properties or accessor properties.
The descriptor parameters are:
- value
Property, which defaults to undefined.
- writable
This property is writable. If set to false, any overwriting of this property is invalid (but does not report an error). This property defaults to true for properties that are defined directly on the object, as in the previous example.
- configurable
If false, any attempts to remove the target property or modify any of the properties (writable, signals, Or Enumerable) of the property will be invalidated. The default value of this property is true for properties that are directly defined on the object, as in the previous example. .
- enumerable
Whether it can be iterated in a for-in loop or enumerated in object. keys. For properties that are defined directly on the object, as in the previous example, this property defaults to true.
- get
Once the target object accesses the property, the method is called and the result is returned. The default is undefined.
- set
This method is called once the target object sets the property. The default is undefined.
31. What is the difference between Object. DefineProperty and ES6 Proxy?
A: The advantages of Proxy are as follows
- Proxies can directly listen on entire objects rather than properties.
- Proxy can directly listen for array changes.
- Proxy has 13 intercepting methods, such as ownKeys, deleteProperty, and HAS, which Object. DefineProperty does not have.
- Proxy returns a new Object, we can only operate on the new Object to achieve the purpose, but object.defineProperty can only traverse the Object properties directly modify;
- Proxy as the new standard will continue to be the focus of browser manufacturers on performance optimization, which is the rumored performance dividend of the new standard.
The advantages of object.defineProperty are as follows
- Good compatibility, support IE9, but Proxy has browser compatibility issues and cannot be polished with Polyfill.
Object.defineproperty has disadvantages:
- Object.defineproperty can only hijack the properties of an Object, so we need to iterate over each property of each Object.
- Object.defineproperty cannot listen to arrays. We listen on the array by overwriting the data in seven ways that can change the data.
- Object. DefineProperty also cannot listen on es6 generated Map,Set data structures.
- Object.defineproperty also cannot listen for add and delete operations. It is implemented in response with vue.set () and vue.delete.
32. What are the usage scenarios of Symbol, Map, and Decorator in ES6? Or in which library source code have you seen these apis used?
Answer: use scenario too much, business also use every day, slightly.
33. Why use TypeScript? What are TypeScript’s advantages over JavaScript?
A: First of all, it doesn’t have to be TS. Large business products and many people working together to write a lot of business code are not suitable for TS.
Advantages: 1. Provides efficient development tools for JavaScript, ides, and practices such as static checking. 2. Others such as powerful type system, generic support, module support, etc. (minor)
34. What’s the difference between const and readonly in TypeScript? What is the difference between constants and enumerations? What are the differences between interface and type aliases?
The difference between const and readonly
- Const is a compile-time constant, and readonly is a runtime constant
- Const can declare only primitive, enumerated, and string types. Readonly The value is unlimited
- Const data is inherently static, so there is no need to add a static flag
- Readonly is a runtime variable that can be assigned only once. A special case is that you can assign once in the definition and again in the constructor
The difference between enumerations and constant enumerations: constant enumerations are defined by using a const modifier on the enumeration. Unlike regular enumerations, they are removed at compile time. Constant enumerators are inlined where they are used. This is possible because constant enumerations are not allowed to contain computed members; As shown in the example above, there is no Size variable at runtime, so constant enumerations provide a performance boost.
The difference between interface and type aliases:
- Type aliases can be used for other types (union types, tuple types, primitive types (primitive values)) that interface does not support
- Nterface can be defined multiple times and is considered to merge all declared member types not supported
- Type can generate mapping types using the in keyword, but interface cannot.
- The default export mode is different
35. What is the use of the any type in TypeScript?
A: Any is an arbitrary type that can evolve TypeScript into the powerful AnyScript.
36. What’s the difference between any, never, unknown, and void in TypeScript?
A: Any is an arbitrary type. Never indicates the type of a value that will never exist. It can be assigned to any type, but it cannot be assigned to any type other than any and unknown. In addition, it is not allowed to execute methods on variables of unknown type (any does). Void indicates no type, as opposed to any, which has no type and should return no value or undefined if it is a function
Can interface declare Function/Array/Class (Indexable) in TypeScript?
A: Yes, interfaces can describe any form of JavaScript object, including functions.
An interface can also be implements by a class. In this case, you declare that an interface contains various properties. You need a class to implement them.
38. Can types be declared in TypeScript using String, Number, Boolean, Symbol, Object, etc.?
A: you can
39. What is the difference between this in TypeScript and this in JavaScript?
A: This cannot be used undeclared. When writing a function, declare this first in the function
40. What are the considerations for using Unions in TypeScript?
A: The value of a union type can be one of multiple types. When TypeScript is not certain what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type (intersection).
41. How does TypeScript design Class declarations?
A: TypeScript type declarations are very flexible, which means that a thousand Shakespeares can produce a thousand Hamlets. In order to achieve better maintainability in team work, we should practice the following three principles as much as possible:
- Generic types are superior to union types
First, the type definition limits getSmallPet. From the logic of the code, it returns an animal that does not lay eggs. The return type refers to Fish or Bird. But what if I just want to pick one bird out of a flock that doesn’t lay eggs? By calling this method, I can only get a magical creature that could be a Fish or a Bird.
Second, the code is repetitive and difficult to expand. I’d like to add a tortoise, for example, I have to find all similar Fish | Bird place, and then modify it into Fish | Bird | Turtle
Third, type signatures do not provide logical correlation. We will have a look at the type signatures, couldn’t see why there is a Fish | Bird rather than other animals, they are two exactly what is the relationship between logic and to be here
- Making good use of Typeof derivation is superior to custom types
- Making good use of built-in utility functions is better than repeating declarations
42. How to associate Key types in TypeScript?
Answer: With mapped type, no extra attributes can be added after use, use type and operation to solve.
type Props = {
[key inLink]: U; } and {type: string; }Copy the code
43. The TypeScript? .,?? ,! The meaning of., _, ** and other symbols?
A:? : indicates that the property or parameter is optional! : indicates mandatory parsing (telling the typescript compiler that there must be a value here), and uses after variables! : indicates that null and undefined are excluded from type inference. If?? The expression to the left of the operator is evaluated as undefined or null, and the value to the right is returned; Otherwise, the value to the left of it is returned
44. What are the predefined conditional types in TypeScript?
A:
Exclude<T, U> -- Exclude all types from T that can be assigned to U. Extract<T, U> Extract the types in T that can be assigned to U. NonNullable<T> -- delete from Tnullandundefined. ReturnType<T> -- Gets the return value type of the function. InstanceType<T> -- gets the InstanceType of the constructor type.Copy the code
45. How to load TypeScript modules?
A: Typescrit modules are similar to es6 modules and provide conversions to AMD, ES6, UMD, CommonJS, and System. When you load typescript on demand, also known as dynamic loading, the compiler detects whether each module will be used in the generated JavaScript. If a module identifier is used only in the type annotation section and not at all in the expression, no code is generated for require this module. Omitting unused references is good for performance and also provides the ability to selectively load modules. The core of this pattern is import id = require(“…”) The) statement gives us access to the exported type of the module. The module loader is invoked dynamically (via require).
Best practices for module loading
- 1. Export at the top level as much as possible
Users should make it easier to use the content your module exports. Too many layers of nesting can become unmanageable, so think carefully about how you organize your code.
- 2. Avoid using namespaces in modules
It is unnecessary to use a namespace in a module. Things exported in a module must not have the same name, and when imported, users will definitely name or directly use it. There is no duplicate name, and using a namespace is unnecessary.
-
3. If only a single class or function is exported, use export Default. As mentioned earlier, default is a good practice.
-
4. If you want to export multiple objects, export them in the top layer
-
5. Specify the name of the import when importing
-
6. Use namespaces when importing large numbers of modules
-
7. Expand with re-export
You may often need to extend the functionality of a module. A common pattern in JS is to extend the original object as JQuery does. As we mentioned earlier, modules are not merged like global namespace objects. The recommended solution is not to change the original object, but to export a new entity to provide new functionality.
46. What do you know about TypeScript type compatibility? Simple understanding of resistance, bivariate, covariant and contravariant?
A: Type compatibility in TypeScript is based on structural subtypes. A structure type is a way of describing a type using only its members. It is in contrast to the name) type. TypeScript structural subtypes are designed according to how JavaScript code is typically written. Because anonymous objects, such as function expressions and object literals, are widely used in JavaScript, it is better to use a structured type system to describe these types than a nominal type system.
-
Covariant: Covariant means that the Comp
type is compatible with that of T.
-
Contravariant: Contravariant means Comp
type compatibility is the opposite of T.
-
Bi-directional Covariant: Bi-directional Covariant means that the Comp
type is bi-directional compatible.
-
Bivariant: invariant means Comp
is not compatible in both directions.
47. Are there any side effects to expanding objects in TypeScript?
A: Expansion is the opposite of deconstruction. It allows you to expand an array into another array, or an object into another object. Expanding objects is much more complicated than expanding arrays. Like an array expansion, it is processed from left to right, but the result is still an object. This means that the properties that appear after the expanded object overwrite the previous properties. Object expansion has some other unexpected limitations. First, it contains only the enumerable properties of the object itself. Basically, when you expand an object instance, you lose its methods:
48. Do interface, type, and enum declarations in TypeScript have scoped functionality?
A: Yes, it is called class scope. Class variables can also be called fields. Class variables are declared inside a class, but outside of the class’s methods, and can be accessed through instantiated objects of the class. Static variable A static class variable that can be accessed directly by the class name
49. Can interfaces or interfaces and classes of the same name be merged in TypeScript?
A: Interfaces with the same name as interface are automatically merged, and classes with the same name as interface are automatically aggregated. However, type cannot be automatically aggregated because type declarations cannot have the same name.
50. How do I get TypeScript projects to import and recognize NPM library packages compiled to JavaScript?
A: You can choose to install the typescript version of your NPM package. NPM install @types/ package name –save, which is the usual name. If you write your own JS library can be written separately. D. ts file
What configuration item information does the tsconfig.json of TypeScript contain?
A:
{
"files": [# specifies the file to compile, relative to the configuration file"core.ts"."sys.ts"."types.ts"."scanner.ts"."parser.ts"."utilities.ts"."binder.ts"."checker.ts"."emitter.ts"."program.ts"."commandLineParser.ts"."tsc.ts"."diagnosticInformationMap.generated.ts"]."exclude": [# specifies that no files need to be compiled"node_modules"."**/*.spec.ts"]."include": [# specifies files to compile; do not configure files,include, default to all. Ts,.d.ts,.tsx except exclude"src/**/*"], # specifies the base configuration file path most of the Settings are compilerOptions, files, include, and exclude. Avoid circular references."extends": "./configs/base"."compilerOptions": {# Tell the TypeScript compiler how to compile"baseUrl": ". /"."paths": {# relative to baseUrl configuration"jquery": ["node_modules/jquery/dist/jquery"]."*": [
"*"."generated/*"]},"rootDirs":[# Leveling path configuration dependency"src/views"."generated/templates/views"]."module": "commonjs"."noImplicitAny": true."removeComments": trueRemove code annotations"preserveConstEnums": true."sourceMap": true
"types": [] # Will not be imported automatically@typesDefinition of package"noResolve":true# will not be imported automaticallyimportDependencies, compiler error"downlevelIteration":true# Demote js syntaxfor..of
"module": "esnext"."moduleResolution": "node"."strictNullChecks": true# opennullTo detect"target":'ES5'
"strictBindCallApply":true
"skipLibCheck":true,}, # the above attributes are common configuration attributes"compileOnSave": falseThe whole project requires compiler support, such as Visual Studio2015 with TypeScript 1.84.+
"typeAcquisition":{# Type definition for the entire project.d.ts"enable":false, # defaultfalse
"include" : ["jquery"."lodash"]
"exclue": ["jquery"."lodash"]},"references":[{# referenced projectpath: 'xxxx'}}]Copy the code
52. How to set module import path aliases in TypeScript?
A: Use the Paths item in tsconfig.json
53. What periodic functions does the React Class component have? What do they do?
A:
-
When constructor() mounts a class component, the constructor is executed first
-
Static getDerivedStateFromProps() is called before the render method is called and will be called both on the initial mount and subsequent updates. It should return an object to update the state, and if null is returned, nothing is updated.
-
Render () renders the real DOM node
-
ComponentDidMount () is called immediately after the component is mounted (inserted into the DOM tree). DOM node dependent initialization should go here. If you need data from a network request, this is a good place to instantiate the request.
Update:
-
Static getDerivedStateFromProps() The same as getDerivedStateFromProps() during the mount
-
ShouldComponentUpdate () is a performance optimization here to reduce shallow comparisons
-
Render () inserts the real DOM node tree
-
GetSnapshotBeforeUpdate () gets useful information from the previous DOM, such as scroll position, in the last render
-
ComponentDidUpdate () Is where you can manipulate the DOM after the component has been updated. If you compare props before and after the update, you can also choose to make a network request here. (For example, the network request will not be executed if the props have not changed)
Uninstall:
ComponentWillUnmount () This is the method called before the component is unloaded and destroyed. You can clear some data here, such as canceling network requests, some data created in componentDidmount, and so on
54. Can React Class requests be initiated in componentWillMount? Why is that?
A: It depends. If it is a server rendering, the data will not be available.
The componentWillMount method is called after constructor but before Render. Code calling setState in this method does not trigger a rerender, so it is generally not used for loading data, and it is rarely used.
Generally from the background (server) to obtain data, will be related to the component to use data load, so all in the componentDidMount method inside. Although loading is independent of the data on the component, can also be done in constructor, but the component state initialization work, is not designed to load data, so all side effects code will be concentrated in the componentDidMount method.
What are the differences between React Class components and React Hooks?
A: Hook code is more readable. The code logic of the same function is split into different lifecycle functions, which makes it difficult for developers to maintain and iterate. React Hooks can be used to combine function code, which is easy to read and maintain.
In the original code, we often use HOC/render/Props to reuse the state of a component and enhance its functionality, increasing the level of the component tree and rendering. In React Hooks, these functions can be implemented with powerful custom Hooks.
The hooks component actually makes react development easier to use, allowing newbies to work on projects without using class components.
56. What are the pros and cons of higher-order functions and custom hooks in React?
A:
Higher-order components actually take a component as an argument and return a new component. Business over-encapsulation of higher-order components can lead to deeper nesting at the component level.
However, custom hooks can be reused without using higher-order components.
57. Briefly explain how useState and useEffect work in React Hook.
Answer: useState returns a stateful value and a function to update it. During initial rendering, the returned state (state) is the same as the value passed as the first parameter (initialState). The setState function is used to update state. It accepts a new state value and queues to rerender the component. During the update process,
-
First render, render()
-
Render will call the App function to get the virtual DIV and create the real DIV
-
The user clicks on the Button and calls setN(n+1). Render is called again
-
Render further calls the App function to get the virtual DIV, Diff, and update the real DIV
-
Each setN calls render again, which in turn calls the App
And useEffect’s running process
-
For the first rendering, put state, deps, etc. in the memoizedState array in order of useState, useEffect, etc.
-
When updating, we take the last recorded values from memoizedState in order.
-
UseState, useEffect and use different data
-
The core of each update is to assign cursor to zero, and then to update in order of hooks from memoizedState, useEffect accepts useState(return the new value) to compare with the old value
58. How to detect rerender, what causes rerender, how to avoid rerender?
A: When the internal data changes, the state changes (by calling this.setstate ()), and the props passed by the parent changes, this causes the component to rerender.
The react lifecycle includes a hook called shouldComponentUpdate, which is the function that is called before render() on rerender. The nextProps and nextState arguments represent the values of the nextProps and state, respectively. When the function returns false, it blocks subsequent calls to render(), preventing the component from rerendering. When the function returns true, the component renders as usual. A setState that does not change the value of state and a parent that does not exchange data will cause the component to be rerendered, but we can prevent both cases by shouldComponentUpdate. ShouldComponentUpdate is not perfect. Only flat objects can be blocked. Consider Immutable. Js (whose basic principle is to return the same reference to an Immutable object and a new reference to a mutable object) or the PureRenderMixin plug-in.
59. What are the useEffect parameters in React Hook and how to detect changes to array dependencies?
Answer: no arguments, empty array, one or more worth arrays, return a function.
The second argument to useEffect can be used to define all the variables it depends on. If one of the variables changes, useEffect runs again. If the array containing variables is empty, useEffect is no longer executed when the component is updated because it does not listen for any variable changes.
60. How does the React useEffect listen for changes to array dependencies?
A: The second argument to useEffect can be used to define all the variables it depends on. If one of the variables changes, useEffect runs again. If the array containing variables is empty, useEffect is no longer executed when the component is updated because it does not listen for any variable changes.
61. What is the relationship between React Hooks and closures?
A:
The first closure is a combination of a function and the lexical context in which it was created. This lexical environment contains all local variables that were accessible at the time the closure was created. The emphasis is on the values of variables at the time the closure was created, and if the values of those variables change after the closure is created, the variables stored in the closure will not be affected.
UseEffect, useMemo, and useCallback all come with their own closures. Each time a component is renderedthey catch the current state (props) in the context of the component’s function. Therefore, each of these three hooks execution also reflects the current state. You cannot use them to catch the last state.
Solution for outdated closures of hooks:
- Adding a dependency
Note that passing an empty dependency and passing no dependency are two concepts: passing the dependency but it is an empty array, and not passing the parameter directly. The former executes only when dependencies change, the latter whenever component data changes.
- Update state as a function
Update the state as a function. Just like react setState, the useState Hook can also modify the state as a function and use the current state value as the function parameter.
- Using useRef
Using the object generated by useRef to bind the state, the update of the state can be directly based on the binding object instead of relying on the state.
- Using useReducer
UseReducer can achieve the same effect as useState, which is updated in function form, and also operates on the basis of the current state at the time of update.
62. How does useState initialize data in React?
A: a function component that is called whenever React performs a render, so the useState inside the function is called every time. In the onMount phase, state is initialized. In the onMount phase, state is initialized. During the onUpdate phase: Update state. UseState returns an array, and the second item in the array is a function that triggers an update to react each time it is called.
63. What are some of your React performance optimization tips?
A:
-
Use shouldComponentUpdate to circumvent redundant update logic
-
PureComponent + Immutable.js
-
The React. Memo and useMemo
64. How are instructions in the Vue 2.x template resolved and implemented?
A: A directive is essentially a JavaScript object with some hook functions attached to it. Whether it is an official directive or a custom directive, a directive passes through one of the following states from the time it is first bound to the element to the time it is finally unbound from the bound element:
- Bind: called only once, the first time a directive is bound to an element. This is where you can do one-time initialization.
- Inserted: Called when the bound element is inserted into the parent node (only ensures that the parent exists, but not necessarily that it has been inserted into the document).
- Update: called when the component’s VNode is updated, but may occur before its children are updated.
- ComponentUpdated: component VNode directive and its children VNode all updated call.
- Unbind: called only once, when a directive is unbound from an element.
We have hook functions for each state, so that we can make instructions do different things in different states. When the virtual DOM renders an update, the create, Update, and deStory hook functions are triggered. This executes the updateDirectives to process the logic of the directive and execute the directive function for the directive to take effect.
65. Briefly explain the full link operation mechanism of Vue 2.x?
A:
- Initialize and mount init, mount
- Compile the template into the render function
- Run render function to generate a Virtual DOM. Render function => VNode tree
- Render function => getter, setter => watcher. update => patch. And a policy for asynchronous updates using queues.
- Finally, patch update view is carried out through diff algorithm
66. What is the framework design of the Element UI?
A:
Supports NPM mode and CDN mode, and supports on-demand introduction, support multi-language, detailed documentation, rich components. (Don’t know)
67. How to understand that Vue is a progressive framework?
A:
What progressive represents is: not doing more than is required.
You can use JSX for development, you can also write templates; You can use the Vue whole family bucket, you can also use it as a lightweight view of a business, as you like, do not insist or advocate.
68. What are the ways to achieve cross-component communication in Vue?
A:
- Father-son communication:
The parent passes data to the child via props, and the child to the parent via events (emit). Communication is also possible through parent/child chains (emit); Communication is also possible through parent/child chains (emit); Communication is also possible through parent/child chains. Ref can also access component instances; Dojo.provide/injectAPI; The children); Ref can also access component instances; Provide/inject API; The children); Ref can also access component instances; Dojo.provide/injectAPI; attrs/$listeners
- Brother correspondence:
Bus; Vuex
- Cross-level communication:
Bus; Vuex; Dojo.provide/inject API, attrs/attrs/attrs/listeners
69. How does responsive data in Vue enable listening for the deeper properties of an object?
A:
Deep listening on objects can be achieved by using watch with deep:true
70. What’s the difference between MVVM, MVC, and MVP? What are the application scenarios? ,
A:
MVC is a pattern for creating Web applications using Model View Controller (MVC) design.
- Low coupling
- High reusability
- Low lifecycle cost
MVP evolved from the classic PATTERN MVC. The basic idea is that a Controller/Presenter handles the logic, a Model provides the data, and a View provides the display.
- The model is completely separate from the view, and we can modify the view without affecting the model
- Models can be used more efficiently because all interaction takes place in one place — inside the Presenter
- We can use a Presenter for multiple views without changing the Presenter logic. This feature is very useful because the view changes more often than the model.
- If we put the logic in a Presenter, then we can test the logic outside of the user interface (unit testing)
MVVM is essentially an improved version of MVC. MVVM abstracts the state and behavior of its views, allowing us to separate the View UI from the business logic.
- Low coupling
- reusability
- Independent development
- testable
71. What is the MVVM framework?
A: MVVM is characterized by data-binding: Changes in the View are automatically reflected in the View Model and vice versa. This way the developer doesn’t have to deal with receiving events and View updates; the framework does that for you.
72. What are the functions of Vue CLI 3.x? Vue CLI 3.x plug-in system?
A:
The plug-in system is an NPM package that provides optional functionality for vUE projects such as Babel/TypeScript translation, ESLint integration, unit, and E2E testing
73. How is Webpack assembled in Vue CLI 3.x?
A:
Compared to Vue-CLI2, the main thing about CLI3 is that the generated project has no files for webpack configuration. The scaffolding of CLI3 encapsulates most of the webpack configuration, making the generated project more clear, but in the development of the inevitable needs of their own personality, to add some of their own project configuration, just in the root directory of the project to create a vue.config.js file. Webpack uses resolve.alias to do this. To modify webPack configuration in vue.config.js, use the configureWebpack method.
74. How does Vue 2.x support TypeScript syntax?
A:
- Configure ts-loader and tsconfig
- Added type extension for TS to recognize vUE files
- To change the script in the vue file to ts, you need to add several ts extended packages, such as vue-property-decorator
75. How do YOU configure your environment so that your JavaScript projects support TypeScript syntax?
A:
- Use Babel’s @babel/plugin-transform-typescript plugin.
- Use ts-Loader in conjunction with the official typescript library.
How do I Lint TypeScript? What’s the difference between ESLint and TSLint?
A:
ESLint and TSLint are both syntax checkers for Javascript. ESLint or TSLint are commonly used to solve a series of dissonant problems caused by different code styles in team development.
ESLint supports configuration files in several formats:
- JavaScript: Use.eslintrc.js and output a configuration object.
- YAML: Use.eslintrc.yaml or.eslintrc.yml to define the structure of the configuration.
- JSON: Use.eslintrc. JSON to define the structure of the configuration. ESLint’s JSON files allow javascript-style comments.
- Deprecated: Use.eslintrc, which can be either JSON or YAML.
Package. json: Create an eslintConfig property in package.json and define your configuration there.
TSLint is used with Typescript. There are some framework issues with the way TSLint executes rules that affect performance, and fixing these issues can break existing rules. ESLint performs better, and the community generally has ESLint’s rule configurations (such as those for React and Vue) rather than TSLint’s rule configurations.
77. How does Node.js support TypeScript syntax?
A:
Node is a runtime environment based on the Chrome V8 engine that enables JavaScript to run on the server side. TS eventually compiles to JS, which then generates bytecode -> machine code. Node.js supports TS syntax. Is there any doubt that it is compiled to JS?
78. How does TypeScript automatically generate library package declarations?
A:
Compile options. Here find options related to generating the corresponding.D. ts files and declaration files. These include:
- declaration
- declarationDir
- types
- typeRoots
After configuring the tsconfig.json file, running NPM run build again will generate the types folder in the project root directory. This folder mainly stores the automatically generated TypeScript declaration files.
79. What limitations do Babel have on TypeScript support?
A:
Using Babel-preset -typescript allows for the coexistence of JavaScript and typescript at the same stage of the compilation process. With the Babel Preset configuration, it is easier to achieve the desired smooth transition from JS project to TS project.
However, there are certain requirements for Babel, and different versions of Babel have compatibility issues with Monorepo, especially when referencing modules from subrepo, which can cause the Babel configuration to be incorrectly obtained.
80. What is the difference between Loader and Plugin in Webpack?
A:
In WebPack, Loader is responsible for completing the loading of various resource modules in a project, so as to realize the modularity of the whole project. Plugin is used to solve other automatic work except the packaging of resource modules in a project, while Loader only works in the module loading process. The scope of plug-ins can touch almost every aspect of Webpack’s work.
81. How to support Sourcemap positioning in Webpack similar to JSX syntax?
A:
// See the back of the paper
Copy the code
82. How do I specify the import address when publishing Npm packages?
A:
// See the back of the paper
Copy the code
83. How to publish a development project specific folder as the Npm package root directory?
A:
The directories attribute in package.json can be used to change the directories in the NPM directory.
How do I publish an Npm package that supports Tree Shaking?
A:
Typically, people block files in the node_modules directory when compiling code using the Babel plug-in of the packaging tool. Because by convention the modules you publish to NPM are based on the ES5 specification, configuring the Babel plug-in to block the node_modules directory can greatly improve compilation speed. However, users who use our published es6-based packages must configure complex filtering rules to whitelist our packages for compilation.
If the user is using our package in a NodeJS environment, it is highly likely that the packaging step is not even taken. If the user’s NodeJS environment also happens not to support the ES6 module specification, the code will report an error.
For both of these reasons, the pkg.module field should point to a module based on the ES6 module specification, written in ES5 syntax. Based on the ES6 module specification, users can enjoy the benefits of Tree Shaking when using our package; It is written in ES5 syntax so that users can safely shield the node_modules directory when configuring Babel plug-ins. This is equivalent to releasing versions of both module specifications in a single package.
When the packaging tool encounters our module:
- If it already supports the pkg.module field, the version of the ES6 module specification is preferred, enabling the Tree Shaking mechanism.
- If it does not already recognize the pkg.module field, it will use the version we have compiled to the CommonJS specification without hindering the packaging process.
85. What is the function of peerDependencies in the Npm package?
A:
The purpose of peerDependencies is to prompt the host environment to install the packages that meet the dependencies specified in the plug-in peerDependencies, and then always refer to the NPM packages installed in the host environment when the plug-in imports or requires the dependent packages. Finally, the inconsistency between the plug-in and the dependent packages is resolved.
86. How to elegantly debug Npm packages that need to be released?
A:
- Enter the NPM link command in the console structure of the NPM package directory to map the current package to a local global NPM package.
- Enter the NPM link package name on the console in the referenced directory structure. This command will redirect the locally referenced NPM package path to the global NPM package.
- The global NPM package acts as a relay station between the edit area and the reference area.
87. How to generate version logs when designing some library packages?
A:
NPM Run Changelog Version log information automatically generated
Do you know about Git (Submodule)? What about Git submodules?
A:
A submodule is a way of connecting the development with the requirements and embedding the requirements document into the developer’s project as a submodule project. The use of submodules can reduce the need or the designer’s Git operation, and can promptly publish doc documents to the project directory file, without any impact on the developer’s project.
How do I modify the Commit information in Git?
A:
Git rebase -i <commit id> Lists the commits
- Find the commit record you want to change, change pick to Edit or e, :wq, save and exit
- Git commit –amend, save and continue to the next Git rebase –continue, until all is finished
- The middle also can skip or exit git rebase (- skip | – abort)
90. How to undo Git Commit and save previous changes?
A:
- Look at the commit
git log --pretty=oneline
- Undo to the previous COMMIT, but save the current changes.
git reset --soft <commit>
- Modification succeeded. Rebuild the branch and commit.
How can Git ignore files that have been committed?
A:
- Delete files from track (files that have been committed)
- Add the ignore rule to the.gitignore file
Gitignore: git commit -a -m “Add ignore rule”
- Pushing to the remote repository makes the ignore rule available to other developers
92. How to specify Git Commit information when using Git?
A:
Use Commitizen. Commitizen is a tool for writing Commit Messages that conform to the above standard. Commit information is checked for push, using a regular pattern to check for matches (such as using the Angular Git specification), and push is not allowed if it does not.
93. Describe the structure of an Angular submission specification?
A:
The commit format is as follows:
<type>: <subject> <BLANK LINE> <body> type - The type of commitCopy the code
Feat: new features
Fix the problem
Docs: Modify a document
Style: Modify the code format (without affecting logical functions such as formatting, adding semicolons, etc.)
Refactor: Refactoring code (fixing bugs or adding new features doesn’t fall into this category)
Perf: Improves page performance
Test: Adds/modifies test cases
Chore: Tool related modifications (including but not limited to documentation, code generation, etc., modified README, WebPack configuration files, etc.)
Deps: Upgrade dependencies
Subject – A clear, one-sentence description of what this submission does
Body – Supplementary subject, adding related factors such as cause and purpose, optional.
How does 94.Com MIT Information associate with Github Issues?
A:
When you make a commit and use #issue in the Commit message, such as #8, Github will automatically associate issue 8 with the commit. This also works when writing a comment on Github, and when confirming a merge you can use the following command to close the issue.
fixes #xxx
fixed #xxx
fix #xxx
closes #xxx
close #xxx
closed #xxx
Copy the code
What is the role of Git hooks in a project?
A:
Git Hooks are custom scripts, so they implement functions related to their Git actions. Here are a few simple examples:
- Multiple development code syntax, specification mandatory unity
- Commit Message format, whether it conforms to a certain specification
- Test case detection if required
- Notify all developers of new updates to the server code
- Projects are automatically packaged after the code is committed (after Git receive)
- And so on…
96. What are the functions of client and server hooks in Git hooks?
A:
Client-side hooks are called for operations such as commit and merge, while server-side hooks are used for networking operations such as receiving pushed commits.
What are the common hooks in Git hooks?
A:
ClientSide hooks:
-
Pre-commit: execute this hook first when the commit action is performed. You can use this hook to perform some checks, such as code style checks, or to run tests first.
-
Prepare -commit- MSG: this hook will be triggered before the message needs to be entered during commit. You can use this hook to customize your own default message message.
-
Commit-msg: this hook is triggered when the user enters the commit message. You can use this hook to verify the message, such as whether it complies with the regulations, whether there is a CR, etc.
-
Post-commit, when the commit is triggered, you can use this hook to send notification and so on.
-
This hook can be used to reject all commits that have been pushed for rebase operations.
-
Post-merge, when the merge succeeds, this hook will be triggered.
-
Pre-push, when push, remote refs are updated, but triggered before all objects are transferred.
-
Pre-auto-gc is triggered when git gC-auto is executed. It’s nice to do some validation or backup before garbage collection.
ServerSide hooks:
-
Pre-receive, which is performed when a push action is received.
-
Update is also executed before a push action is received, but may be executed multiple times, once for each branch.
-
Post-receive: this hook will be triggered when the push action has been completed. You can use this hook to push notification, such as sending emails, notifies the continuous build server, etc.
98. What is the difference between pre-commit and commit-msg hooks? What can each be used for?
A:
Pre-commit is one of the client-side hooks that I’ll introduce next. A pre-commit is executed after a Git add commit and then during a Git commit. A pre-commit is executed after a Git add commit and then during a Git commit. This hook allows you to check the code to be submitted, optimize the format of the code, or compress the submitted images.
Git must write a Commit message every time the code is committed, otherwise it is not allowed to Commit.
99. How do tools like Husky and Ghook make Git hooks?
A:
The code is checked by Husky and git hooks before committing. If the commit does not comply with Angular specifications, the submission will fail.
How to design a generic Git Hook?
A:
With Commitizen, use Git CZ instead of Git COMMIT to commit Message of composite Angular specification, specification team git specification. Before the code is submitted, husky and Git hook will verify the submitted information. Once the submitted information does not comply with the git specification of the team and the regular match fails, the submission will fail.
101. Can Git hooks be designed using Node scripts? How?
A:
You can. Hooks are stored in the hooks subdirectory of Git. That is.git/hooks in most projects. When you initialize a new repository with Git init, git places sample scripts in this directory by default. In addition to being called, these scripts reveal the parameters passed when fired. All of the examples are shell scripts, and some of them are mixed with Perl code, but any properly named executable script will work fine — you can write them in Ruby or Python, or whatever. The names of these examples all end in.sample, and if you want to enable them, you’ll have to remove this suffix first.
For example in the Node. Js to write a refused to submission is not solve the conflict of hook, write this hook because in many cooperative projects, always unavoidably will encounter conflict of files, and some colleagues didn’t find all the conflicting files and one by one to solve, this hook will be when the commit to check whether there is a conflict, If there are conflicts, all conflicts will be found, and the error file will be displayed, and the commit will be rejected.
#! /usr/bin/env node
// Check for conflicts before committing. If so, process.exit(1)
const execSync = require('child_process').execSync
// Git generates the following format for all conflicting files, so write a regex that detects conflicting files
const isConflictRegular = "^<<<<<<<\\s|^=======$|^>>>>>>>\\s"
let results
try {
// The git grep command executes perl's re to match all files that match the conflicting conditions
results = execSync(`git grep -n -P "${isConflictRegular}"`, {encoding: 'utf-8'})}catch (e) {
console.log('No conflict found, wait for commit')
process.exit(0)}if(results) {
console.error('Conflicts found, please resolve them before submitting, conflicting files:')
console.error(results.trim())
process.exit(1)
}
process.exit(0)
Copy the code
Copy this file to.git/hooks/pre-commit and run chmod 777 pre-commit to check for conflicts with each commit.
102. How do I ensure that code uploaded by someone has no Lint errors? How do I ensure that code is built without Lint errors?
A:
When building projects using the CLI, check Use ESLint to Lint your code. In the.eslintrc.js file, find rules in the file where we can define some rules for code checking
'semi': ['error'.'always']
Copy the code
Common rules
'rules': {
"comma-dangle": ["error"."never"].// Whether to allow ending commas in objects
"no-cond-assign": 2.// Assignment operators are not allowed in conditional statements
"no-console": 2.// The console statement is not allowed
"no-constant-condition": 2.// A conditional statement does not allow a constant quantity in a condition
"no-control-regex": 2.// Control characters are not allowed in regular expressions
"no-debugger": 2.// Do not allow debugger statements
"no-dupe-args": 2.// Do not allow duplicate arguments when defining a function
"no-dupe-keys": 2.// Duplicate keys are not allowed in the object
"no-duplicate-case": 2.// Duplicate case labels are not allowed in the switch statement
"no-empty": 2.// Empty code blocks are not allowed
"no-empty-character-class": 2.// Empty character groups are not allowed in regular expressions
"no-ex-assign": 2.// It is not allowed to reassign exception variables in a try catch statement
"no-extra-boolean-cast": 2.// Do not allow unnecessary Boolean conversions
"no-extra-parens": 0.// Do not allow unnecessary parentheses
"no-extra-semi": 2.// Do not allow unnecessary semicolons
"no-func-assign": 2.// Reassigning function declarations is not allowed
"no-inner-declarations": ["error"."functions"].// You are not allowed to declare functions in nested code blocks
"no-invalid-regexp": 2.// Invalid regular expressions are not allowed in the RegExp constructor
"no-irregular-whitespace": 2.// Irregular Spaces are not allowed
"no-negated-in-lhs": 2.// It is not allowed to reverse the leftmost operand in an in expression statement
"no-obj-calls": 2.// It is not allowed to call global object properties as functions
"no-regex-spaces": 2.// Multiple consecutive Spaces are not allowed in a regular expression
"quote-props": 2.// Whether attribute names in an object need to be enclosed in quotes
"no-sparse-arrays": 2.// No empty positions are allowed in the array
"no-unreachable": 2.// Do not allow impossible reachable statements after return, throw, continue, or break statements
"use-isnan": 2.// Use isNaN() when asking to check NaN
"valid-jsdoc": ["error", {
"requireReturn": false."requireParamDescription": false."requireReturnDescription": true}].// Force JSDoc comments
"valid-typeof": ["error", {
"requireStringLiterals": true}].// Enforce a valid string when comparing typeof expressions
"block-scoped-var": 2.// Put variable declarations in the appropriate code block
"complexity": 0.// Limit the complexity of conditional statements
"consistent-return": 2.// Force the return statement to return a value with or without a return value
"curly": ["error"."all"].// Enforce the curly brace style
"default-case": 0.// The default statement is required in the switch statement
"dot-notation": ["error", {"allowKeywords": false."allowPattern": ""}].// Use a dot to get object properties
"eqeqeq": ["error"."smart"].// Use strict equals when comparing
"no-alert": 1.// Do not allow alert, confirm, prompt statements
"no-caller": 2.// Arguments. Callee and arguments.caller attributes are not allowed
"guard-for-in": 0.// Monitor the for in loop to prevent unexpected situations
"no-div-regex": 2.// You cannot use regular expressions that look like division
"no-else-return": 0.// If the if statement has a return, don't put the return in the else
"no-labels": ["error", {
"allowLoop": false."allowSwitch": false}].// Label statements are not allowed
"no-eq-null": 2.// Null is not allowed with == or! =
"no-eval": 2.// Not allowed to use eval()
"no-extend-native": 2.// Extension of native objects is not allowed
"no-extra-bind": 2.// Do not allow unnecessary function bindings
"no-fallthrough": 2.// Do not allow the switch to execute all cases in order
"no-floating-decimal": 2.// Floating-point numbers are not allowed to be missing
"no-implied-eval": 2.// Not allowed to use implicit eval()
"no-iterator": 2.// The __iterator__ attribute is disallowed
"no-lone-blocks": 2.// Do not allow unnecessary nested code blocks
"no-loop-func": 2.// Function declarations in loops are not allowed
"no-multi-spaces": 2.// No extra Spaces are allowed
"no-multi-str": 2.\ is not allowed to wrap a string
"no-global-assign": 2.// Redistribution of native objects is not allowed
"no-new": 2.// Do not allow new instances to be unassigned or uncompared
"no-new-func": 2.// New Function is not allowed
"no-new-wrappers": 2.// New String, Number, and Boolean objects are not allowed
"no-octal": 2.Octal literals are not allowed
"no-octal-escape": 2.// Octal escape sequences are not allowed
"no-param-reassign": 0.// Not allowed to reassign the function argument "no-proto": 2, // not allowed to use the __proto__ attribute
"no-redeclare": 2.// Do not allow repeated declarations of variables
"no-return-assign": 2.// Do not allow allocation statements in return statements
"no-script-url": 2.// Not allowed to use javascript:void(0)
"no-self-compare": 2.// Don't allow yourself to be compared to yourself
"no-sequences": 2.// Comma expressions are not allowed
"no-throw-literal": 2.// Not allowed to throw literal errors
"no-unused-expressions": 2.// Do not allow useless expressions
"no-void": 2.// The void operator is not allowed
"no-warning-comments": [1, {"terms": ["todo"."fixme"."any other term"]}], // Warning remarks are not allowed
"no-with": 2.// The with statement is not allowed
"radix": 1.// When parseInt is used, it is mandatory to use the base to specify whether it is decimal or some other base
"vars-on-top": 0.Var must be placed at the top of the scope
"wrap-iife": [2."any"].// Execute the parenthesis style of the expression immediately
"yoda": [2."never", {"exceptRange": true}].// The yoda condition is not allowed in the if condition
"strict": [2."function"].// Use strict mode
"no-catch-shadow": 2.// Do not allow the try catch statement to accept err variable with the same name as the external variable "no-delete-var": 2, // Do not allow the delete operator
"no-label-var": 2.Tags and variables are not allowed to have the same name
"no-shadow": 2.// A variable in an outer scope cannot have the same name as a variable or parameter in the scope it contains
"no-shadow-restricted-names": 2.// the js keyword and reserved word cannot be used as the function name or variable name
"no-undef": 2.// Undeclared variables are not allowed
"no-undef-init": 2.// It is not allowed to assign undefined to a variable when initializing it
"no-undefined": 2.// Use of undefined as an identifier is disallowed
"no-unused-vars": [2, {"vars": "all"."args": "after-used"}].// Do not allow variables or parameters that are not used after recording
"no-use-before-define": [2."nofunc"].// Do not allow the variable "indent" to be used before it is defined: 2, // enforce a consistent indent style
"brace-style": [2."1tbs", { "allowSingleLine": false}].// Brace style
"camelcase": [2, {"properties": "never"}].// Enforce hump naming rules
"comma-style": [2."last"].// Comma style
"consistent-this": [0."self"].// This is the same style when getting the current environment
"eol-last": 2.// The file ends with a newline
"func-names": 0.// Function expressions must have names
"func-style": 0.// Function style, which specifies that only function declarations or function expressions can be used
"key-spacing": [2, {"beforeColon": false."afterColon": true}].// Spaces before and after colons in object literals
"max-nested-callbacks": 0.// Callback nesting depth
"new-cap": [2, {"newIsCap": true."capIsNew": false}].// Capitalize the constructor name
"new-parens": 2.// The new constructor must have parentheses
"newline-after-var": 0.// The variable declaration must be followed by an empty line
"no-array-constructor": 2.// Array constructors are not allowed
"no-inline-comments": 0.// Inline comments are not allowed
"no-lonely-if": 0.// Do not allow the else statement to contain only if statements
"no-mixed-spaces-and-tabs": [2."smart-tabs"].// Mixed tabs and Spaces are not allowed
"no-multiple-empty-lines": [2, {"max": 2}].// There can be no more than two blank lines
"no-nested-ternary": 2.// Nested ternary operators are not allowed
"no-new-object": 2.// Disallow new Object()
"fun-call-spacing": 2.// When a function is called, there must be no space between the function name and ()
"no-ternary": 0.// Ternary operators are not allowed
"no-trailing-spaces": 2.// No space is allowed at the end of a line
"no-underscore-dangle": 2.// Identifiers starting with an underscore are not allowed
"no-extra-parens": 0.// Redundant parentheses are not allowed
"one-var": 0.// Force variable declarations together
"operator-assignment": 0.// Assignment operator style
"padded-blocks": [2."never"].// Whether the first and last lines in a block are blank
"quote-props": 0.// Attribute names in object literals are quoted
"quotes": [1."single"."avoid-escape"].// Quote style
"semi": [2."always"].// Enforce the semicolon ending of statements
"semi-spacing": [2, {"before": false."after": true}].// There is space before and after the minute
"sort-vars": 0.// Sort variables when declaring them
"space-before-blocks": [2."always"].// The space before the block
"space-before-function-paren": [2, {"anonymous": "always"."named": "never"}].// The space before the parentheses when the function is defined
"space-infix-ops": [2, {"int32Hint": true}].// The space around the operator
"keyword-spacing": 2.// Spaces before and after the keyword
"space-unary-ops": [2, { "words": true."nonwords": false}].// Do not add Spaces before and after unary operators
"wrap-regex": 2.// Regular expression literals are enclosed in parentheses
"no-var": 0.// Use let and const instead of var
"generator-star-spacing": [2."both"].// Generator function before and after the space
"max-depth": 0.// Nested block depth
"max-len": 0.// The maximum length of a line, in characters
"max-params": 0.// The maximum number of parameters a function can take
"max-statements": 0.// There are at most several declarations in a function
"no-bitwise": 0.// Bitwise operators are not allowed
"no-plusplus": 0 // The ++ -- operator is not allowed
}
Copy the code
How to perform Lint validation prompts in Vs Code? How to format save in Vs Code?
A:
- Open the terminal and run NPM install eslint -g to install ESLint globally.
- Vscode installs the plug-in
- Scode extension Settings
104. What’s the difference between ESLint and Prettier? Do they cause problems when they work together?
A:
Neither of these addresses the same problem; ESLint mainly addresses code quality issues; Prettier mainly solves code style problems. The two together can cause problems.
Needs to be addressed: Eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier eslint-config-prettier Eslintrc “prettier” is the last extends in.eslintrc.
// .eslintrc
{
"extends": ["prettier"] "Prettier" = "prettier"; "prettier" = "prettier"
}
Copy the code
(Optional, recommended) Then enable eslint-plugin-prettier, adding prettier rules to ESLint as a plug-in for prettier. And by the way, why “optional”? “When you use Prettier + ESLint,” Prettier “takes over all formatting issues.” Disable ESLint, “Prettier” takes over all formatting issues. So why do we need this plugin? Actually because we expect the source of the error is still ESLint, use this, equivalent to a Prettier recommended format problem configuration to ESLint rules of writing, this is equivalent to the source of the problem can be unified code.
// .eslintrc
{
"plugins": ["prettier"]."rules": {
"prettier/prettier": "error"}}Copy the code
Put the above two steps together and you have the following configuration, which is the official recommended configuration
// .eslintrc
{
"extends": ["plugin:prettier/recommended"]}Copy the code
How to effectively identify ESLint and Prettier format rules that might conflict? How to resolve such rule conflicts?
A:
- Right mouse button, select document format setting mode.
- From the drop-down list, select Prettier. “Prettier” is used to format the code.
- CTRL + Shift + P, then select format document from the drop down list.
“Prettier”, an prettier format for prettier, an prettier format for prettier, an prettier format for prettier. You can use prettier to format code, and esLint to correct parts of the code that don’t conform to ESLint rules.
106. How can ESLint print validation errors in real time for hot Module replacement in normal scaffolding projects?
A:
Ctrl+ S/Command + S automatically fixes formatting errors in code by reading Eslint rules from the project root directory.
107. What do you know about SourceMap?
A:
SourceMap is an information file that stores the location information before packaging. That is, for every position in the transformed code, there is the position before the transformation. With it, when an error occurs, the browser console will display the original code where the error occurred, rather than the converted code, and clicking on the error message will jump directly to the original code location. Easy to locate and solve problems.
108. How to debug Node.js code? How to debug Node.js TypeScript code? How do I debug Node.js code in the browser?
A:
Starting with NodeJs8, nodejs8 removes _debugger and integrates inspect inside. Previously, online debugging with Nod-inspect is no longer available.
- Run Nodejs in INSPECT mode on the server
node --inspect-brk=0.0. 0. 0:8080 index.js
Copy the code
- Open chrome and type in the address bar
chrome://inspect
In the dialog box that is displayed, enter IP :port.
109. List all the build tools you know and what are their pros and cons? How should these build tools be selected in different scenarios?
A:
Grunt, Gulp, Webpack, vite, Rollup
110. What is the difference between a user and a workspace in a VS Code configuration?
A:
VS Code provides two Settings:
-
User Settings: This method applies to all projects opened by the user.
-
Workspace Settings: A workspace is a folder opened with VS Code. Within this folder, a hidden folder named.vscode is created, which contains the Settings of VS Code that are only applicable to the current directory. The workspace Settings overwrite the user Settings.
“User Settings” applies to all projects the user opens;
Workspace Settings only apply to VS Code Settings for the current directory.
111. Can VS Code plug-ins only work for the current project?
A:
Of course not.
112. What types of tests do you know?
A:
Functional test, performance test, interface test
113. What testing frameworks do you know?
A:
Selenium, Cypress, Appium, Requests, Jmeter, Mitmproxy
114. What is e2E testing? What testing frameworks are available for E2E?
A:
End-to-end testing;
Cypress, Selenium, Puppeteer, Nightwatch
115. Suppose you have an insertion sort algorithm. How do you unit test it?
A:
// See the back of the paper
Copy the code
116. How does the CDN service achieve network acceleration?
A:
The working principle of CDN is to cache the resources of your source site to CDN nodes located all over the world. When users request resources, the resources cached on the node will be returned to the nearest user. It is not necessary for each user’s request to be returned to your source site for obtaining, so as to avoid network congestion, relieve the pressure on the source site, and ensure the speed and experience of users’ access to resources.
117. Does WebSocket use TCP or UDP?
A:
Websocket is based on TCP, the webSocket protocol is in the TCP/IP protocol cluster application layer, and HTTP in the same layer.
118. What are simplex, half-duplex and full-duplex communications?
A:
- Simplex data transmission only supports data transmission in one direction.
- Half-duplex data transmission allows data to be transmitted in two directions, but at one time only one direction is allowed. It is actually simplex communication that switches directions;
- Full-duplex data communication allows data to be transmitted in both directions at the same time. Therefore, full-duplex communication is a combination of two simplex communication modes. It requires the sending device and the receiving device to have independent receive and send capabilities.
119. Briefly describe the HTTP protocol to send a URL request with a domain name protocol transmission process? (DNS, TCP, IP, link)
Answer: omit (too much content)
Give a short and incomplete answer, and wait for the interviewer to ask one question after another.
- The browser gets an HTML text from the request
- The rendering process parses the HTML text and builds the DOM tree
- While parsing HTML, stytle rules are downloaded and built if inline styles or style scripts are encountered, and execution scripts are downloaded if JavaScript scripts are encountered.
- After the DOM tree and style rules are built, the render process merges them into a Render tree.
- The render process begins to layout the render tree, generating a layout tree.
- The rendering process draws the layout tree and generates a drawing record
- The rendering process layers the layout tree, rasterizing each layer separately and producing composite frames
- The rendering process sends the synthesized frame information to the GPU process for display on the page
120. What is forward proxy? What is a reverse proxy?
A:
Agents can be understood as intermediaries in nature. When it is not convenient for A and B to interact, an intermediate role C is often introduced, and THEN C is the intermediary and the agent.
The forward proxy server usually sits between the client and the server and acts like a leapfrog. The target server can be accessed through the proxy server.
In a forward proxy, typically, the client sends a request to the target server, and the proxy server forwards the request to the target server in the middle, and returns the result to the client.
A reverse proxy is the opposite of a forward proxy. The proxy service is on the server side.
To the client, the reverse proxy server is like the target server. The reverse proxy server receives the request from the client, distributes the request to the Intranet server, and returns the result returned by the Intranet server to the client.
The client is not aware of the services behind the reverse proxy, and there is no need for the client to do any setup, just treat the reverse proxy server as a real server.
121. Can cookies be generated on the server? What is the workflow after the Cookie is generated on the server?
A:
You can. Cookies in THE HTTP protocol include Web Cookie and browser Cookie, which is a small piece of data sent by the server to the Web browser. The server sends a Cookie to the browser, which stores it and sends it to the server with the next request. Typically, it is used to determine whether two requests are coming from the same browser, such as when the user remains logged in.
122. What is the difference between Session and Cookie? How to store temporary and permanent sessions?
A:
- Session
The client requests the server, and the server will create a memory space for the request. This object is called the Session object, and the storage structure is ConcurrentHashMap. Sessions compensate for the stateless nature of HTTP by allowing the server to store records of some of the client’s actions during the same Session.
- Cookies
Cookies in THE HTTP protocol include Web Cookie and browser Cookie, which is a small piece of data sent by the server to the Web browser. The server sends a Cookie to the browser, which stores it and sends it to the server with the next request. Typically, it is used to determine whether two requests are coming from the same browser, such as when the user remains logged in.
On the server side, if you do not specify the duration of the session, the value stored in the browser you open is available in the newly opened box and automatically disappears when it is closed (this is actually the session_id, because the session mechanism depends on cookies (and can depend on others).
123. How to prevent XSS attacks when setting cookies?
A:
Set http-only when setting cookies on the server, so that users can avoid obtaining cookies through JS. The following fields are used to set read, write, or send cookies:
- Http-only: Only HTTP or HTTPS requests are allowed to read cookies. The JS code cannot read cookies (document.cookie displays that http-only cookies are automatically filtered out). Cookies are automatically sent when the request is sent.
- Secure-only: Only HTTPS requests are allowed and cookies are automatically sent when requests are sent.
- Host-only: Only websites whose host domain names are consistent with the domain Settings can access the cookie.
Setting cookies can prevent attackers from obtaining the cookies of normal users to impersonate their identities and illegally invoke the website interface.
124. Briefly describe the implementation process of user login free? What security issues might arise? How do I encrypt the user login password?
A:
When a user logs in successfully for the first time, the back end returns a Token. The Token is used to identify the user. Equivalent to the account password. In normal cases, when the front end sends a request to the back end, the back end needs to determine the identity of the user before returning corresponding data to the user. After obtaining the Token, you need to store the Token in a Cookie. Then when you send a request to the server, you take the Token out of the Cookie and carry the Token in the request header. The Token expiration time is long enough. As long as the Token does not expire, users are exempt from login during this period.
Security issues: Other people using the machine, achieve logon-free, cannot authenticate the user’s identity every time they use the application. Provides convenience, loses security check.
The user login password is encrypted. The password is MD5 rather than plaintext transmission.
125. What are some ways to improve the transfer rate in HTTP? What are some common ways to encode content?
A:
- Using compression techniques, the entity body is compressed and the data is parsed at the client.
- Using block transfer encoding, the entity body is transferred into blocks, and when the browser resolves to the entity body, it can be displayed.
Common content encoding methods:
- The zero yards
- Manchester code
- Differential Manchester coding
126. If there is a sudden interruption in the transmission of pictures, how to resume the transmission from the previous interruption after the recovery?
A:
Resumable file,
The front-end work
- Add a different identifier for each file cut block
- When the upload is successful, record the id of the successful upload
- When we pause or fail to send, we can resend the cut files that have not been uploaded successfully
The back-end work
- Receive each cut file, and after receiving successfully, save to the specified location, and tell the front-end to receive successfully
- Receive the merge signal, all the cut files sort, merge, generate the final large file, then delete the cut small file, and inform the front end of the address of the large file
127. What is agency? What is a gateway? What are the functions of proxies and gateways?
A:
A proxy is a middleman. The destination IP address of IP packets sent by a proxy host is a proxy, but it tells the proxy at the application layer what its real requirements are. A Gateway is a device that connects networks based on different communication protocols so that files can be transferred between these networks.
128. Why is HTTPS more secure and reliable than HTTP?
A:
Because HTTPS guarantees transmission security, prevents transmission from being monitored, prevents data from being stolen, and can confirm the authenticity of the site (more on that later). It’s important to note, however, that you can still get caught even using HTTPS, because HTTPS only prevents the user from listening in on the communication without his or her knowledge. If the user actively gives credit, a “middleman” network can be set up, and proxy software can decrypt the transmission.
129. What is symmetric key (shared key) encryption? What is asymmetric key (public key) encryption? Which is safer?
A:
The traditional symmetric encryption requires that both parties in the communication keep the same key, which is used for encryption and decryption. So asymmetric encryption is also called single-key encryption. In asymmetric encryption, different keys are used for encryption and decryption. The keys in asymmetric encryption are classified into public keys and private keys. A public key is as public as the name implies. Anyone can encrypt information with the public key, but only the person with the user’s private key can decrypt the information. Asymmetric encryption has the advantage of avoiding the pain of symmetric encryption, which requires the transmission and storage of the same key.
Is asymmetric encryption necessarily more confidential than symmetric encryption? Not necessarily, because confidentiality varies depending on the length of the key. Moreover, the biggest problem of asymmetric encryption is poor performance and can not be applied to long-term communication.
130. What do you think are the current drawbacks of the HTTP protocol?
A:
HTTP does not have the necessary security features, and the way HTTP is used in today’s Web applications has changed dramatically since its original design. Almost all Web sites today use security features such as session management and encryption, which are not available in THE HTTP protocol.
HTTP as a whole is a generic, pure protocol mechanism. So it has many advantages, but in terms of security is a disadvantage. Take the SSH protocol used for remote login. SSH provides protocol-level authentication and session management. HTTP does not. In addition, in setting up SSH services, anyone can easily create a high level of security service, while HTTP has already set up a server, but to provide Web applications based on the server, in many cases need to be re-developed.
Therefore, developers need to design and develop their own authentication and session management functions to meet the security of Web applications. And designing for yourself means all kinds of implementations. As a result, the level of security is not complete, but the bugs behind the Web applications that are still working are all kinds of security holes that are easily abused by attackers.
131. How do you recognize a form item in React that is rendered with minimal granularity/cost?
A:
First, what features should a rendered form item or component have at the minimum granularity/cost:
- Simple and easy to use
- The parent component manipulates form data through code
- Avoid unnecessary redrawing of components
- Support for custom components
- Support form validation
The form item or component is implemented in three parts:
- Form: Used to pass Form context.
- Field: Form Field component for automatically passing value and onChange to the form component.
- FormStore: Stores form data and encapsulates related operations.
In order to reduce the use of refs while still manipulating the Form data (values, modifications, manual validation, etc.), I took the FormStore, which stores the data, and separated it from the Form component. I created it with new FormStore() and passed it in manually.
If the above criteria are met, the form is considered to be rendered with minimal granularity/cost.
For pages with lots of forms, you can use Lighthouse as a measurement tool to iterate and optimize your pages.
132. What can you think of to control rendering costs during the development of React?
A:
-
Use shouldComponentUpdate to circumvent redundant update logic
-
PureComponent + Immutable.js
-
The React. Memo and useMemo
Using useMemo allows us to have more fine-grained control over the execution logic of function components (especially to avoid costly calculations), and to compensate for the fact that React.memo is not aware of the internal state of functions, which is a big benefit to our overall performance.
133. How is the plug-in system for Vue CLI 3.x designed?
A:
[email protected] uses a plug-in based architecture that conversions some of the core functionality to the CLI while exposing extensible apis for developers to flexibly expand and configure the functionality of the CLI.
There are two important components to the plug-in system:
- @vue/cli, providing CLI command services, such as vue create to create a new project;
@vue/cli provides vue CLI commands that are responsible for setting preferences, generating templates, and installing plug-in dependencies, such as vue create
- @vue/cli-service, provides a local development build service.
@vue/cli-service is an internal core plug-in in the @vue/ CLI plug-in system, providing webPack configuration updates and local development and build services
The former mainly completes the dependency management of plug-ins and the expansion of project templates, etc., while the latter mainly provides services for local development and construction at runtime, and the latter also exists as an internal core plug-in in the whole plug-in system of @vue/ CLI. In the plug-in system, core functions are also pluginized, such as @vue/cli-service built-in basic Webpack configuration, NPM script command and so on.
The @vue/cli-service plug-in system contains several core modules:
- Service. Js provides the base class for the Service. It provides the local development build time in the @vue/ CLI ecosystem: plug-in loading (both internal and project application plug-ins), plug-in initialization, its singleton is shared by all plug-ins, and the plug-in uses its singleton to complete WebPack updates.
- Pluginapi.js provides an object interface for plugins to use in a one-to-one relationship with plugins. The first parameter received by any locally developed plug-in for @vue/cli-service is an instance of the PluginAPI (API) that the plug-in uses to register cli commands, execute corresponding services, update webpack configurations, and so on.
134. How is the plug-in mechanism in Webpack designed?
A:
The purpose of the Webpack plug-in mechanism is to enhance Webpack’s ability to automate builds on projects. In WebPack, Loader is responsible for completing the loading of various resource modules in a project, so as to realize the modularity of the whole project. Plugin is used to solve other automatic work except the packaging of resource modules in a project, while Loader only works in the module loading process. The scope of plug-ins can touch almost every aspect of Webpack’s work.
Webpack’s plug-in mechanism is the most common hook mechanism in software development. The hook mechanism is also particularly easy to understand, and is somewhat similar to events in the Web. There are many links in the whole working process of Webpack. In order to facilitate the extension of plug-ins, Webpack has buried a hook in almost every link. This makes it easy to extend Webpack’s capabilities by mounting different tasks to these different nodes when developing plug-ins.
135. what’s the difference between \r\n (CRLF) and \n (LF)? (You can switch to the lower right corner of Vs Code)
A:
\r\n represents carriage return and line feed (this will move the printed paper up one line and return the next typing position to the far left of the line) \n represents line feed
What is /dev/null used for?
A:
/dev/null: represents a black hole, usually used to discard unwanted data output, or empty files for input streams
- Write useless output streams to the black hole for discarding.
Curl – Iwww.baidu.com 2 > / dev/null | head -l positioning error information to a black hole
- Empty file
cat /dev/null > /home/omc/h.txt
- When writing scheduled tasks, the standard way is to add >/dev/null 2>&1 at the end of all scheduled task scripts so that all output streams (both incorrect and correct) are directed to the empty device discard.
137. How do I set a command alias on a Mac terminal?
A:
- Open edit.bash_profile
- Configure an alias
alias dev="npm run dev"
Copy the code
- Save and then reopen Terminal or execute
138. How do I set environment variables in Windows?
A:
- To view all currently available environment variables, enter set.
- To view an environment variable, enter set variable name. For example, to view the value of the path variable, enter set path
- To modify environment variables, enter set variable name = variable content
- Modify variables (Set to null: To set a variable to null, enter “set variable name =”. Change to another value: Enter “set variable name =% variable name %; Variable content “)
139. Is the Mac file operating system case-sensitive by default?
A:
The default does not discriminate. To do so, select MAC OS Extensions (case sensitive, log format) when reinstalling the system or a separate partition.
140. How to set the absolute path of a file when writing Shell scripts?
A:
SHELL_FOLDER=$(dirname $(readlink -f "$0"))
Copy the code
141. What is the difference between Session and Cookie? How to store temporary and permanent sessions?
A:
- Session
The client requests the server, and the server will create a memory space for the request. This object is called the Session object, and the storage structure is ConcurrentHashMap. Sessions compensate for the stateless nature of HTTP by allowing the server to store records of some of the client’s actions during the same Session.
- Cookies
Cookies in THE HTTP protocol include Web Cookie and browser Cookie, which is a small piece of data sent by the server to the Web browser. The server sends a Cookie to the browser, which stores it and sends it to the server with the next request. Typically, it is used to determine whether two requests are coming from the same browser, such as when the user remains logged in.
On the server side, if you do not specify the duration of the session, the value stored in the browser you open is available in the newly opened box and automatically disappears when it is closed (this is actually the session_id, because the session mechanism depends on cookies (and can depend on others).
142. How do I deploy node.js? How do I handle Session consistency in load balancing?
A:
The topic is too big and the space is limited.
143. How can I improve the stability of Node.js code?
A:
- Ensure process security
Due to a user’s abnormal access or data exception, coupled with the failure of exception handling and security protection, the entire Node.js service was directly restarted, which interrupted all requests and caused poor user experience. (1) Because Node.js uses JavaScript, which is a weakly typed language. Therefore, some process exceptions caused by code logic are often thrown on the live network. Secondly, node.js often leaks memory due to improper use of memory. When the memory reaches 1.4g in 64-bit system (0.7G in 32-bit system), Node.js will crash abnormally. (3) Due to the high frequency of I/O in Node.js, when many I/O handles are enabled but not released in time, process problems will also occur.
- parameters error
With json. parse, it’s natural to parse data from other interfaces or third parties, but we tend to ignore the issue of non-JSON strings and try and catch exceptions.
- other errors
Node.js promises are becoming more and more widely used, so we should pay more attention to the catch of promises. We should handle the catch exception logic for each Promise, otherwise the system will send a warning message. Some common persistent services, such as Socket, Redis, Memcache, etc., need to be handled when the connection is abnormal, if not handled will also cause an exception, such as Socket provides socket.on (‘ error ‘) listening.
- Be aware of memory leaks for service exceptions
Set the maximum number of temporary caches. If the number exceeds the maximum, no cache is used. Set the maximum number of cache handles. If the number exceeds the threshold, no cache is used. Periodically clear the current temporary cache and handle cache.
- Avoid global variables
In general, global variables are not recommended. Global variables must have a certain upper limit and cleaning rules to ensure service security.
- Avoid variable memory leaks in singleton modules
One thing to note is that some modules use the singleton pattern, which returns the object every time it is required. This can also cause memory leaks. This is because the singleton pattern causes a superposition of data accessed by each user.
- The file is not closed after being opened
Generally, after opening the file handle, we should take the initiative to close, if not take the initiative to close, will lead to more and more file handles, thus causing the handle leakage problem.
144. What are the differences between GraphQL and Restful, and what are its advantages?
A:
QraphQL is the aggregation and tailoring of the back-end REST API to the business layer, while REST focuses on the fine-grained split and reuse of the business.
In fact, a middle layer is added to do the pre-processing and post-processing of the front-end request and response, the front-end work is less, the back-end work is not much, but added the middle dependence, the benefit is to avoid the front end and the back end of multiple remote interaction. One problem with GraphQL that is hard to control is query complexity. Parsing granularity needs to be controlled during development, and restful apis are still the best choice for mainstream relational databases. Graphql exactly has the advantage of querying graph structured data, which is the idea behind its name.
145. How does Vue SSR work? How is Vuex data rendered isomorphically?
A:
In Vue SSR, there is a layer of factory functions for creating Vue instance, store and router to avoid cross-contamination of data. Only created and beforeCreate in the life cycle can be executed on the server side, because dom cannot be manipulated on the server side. Server rendering is different from client rendering. You need to create two entries to run on the server and client, and you need webPack to package them separately. The SSR server request does not contain cookies. You need to manually get the browser’s cookie and send it to the server. SSR requires dom structure specification because the browser automatically adds some structure such as tbody to the HTML, but when the client confuses the HTML put back by the server, it does not add these tags, resulting in a mismatch between the confused HTML and the HTML rendered by the browser.
For homogeneous applications, we must share routing, model components, and data models between client and server. Vuex is the key to sharing state between our client and server. We can not use Vuex, but we have to implement a set of data prefetch logic. Try encapsulating an EventBus that can be shared between components. Export our EventBus in main.js for two entries. Here are our two entries. The server is used to match our component and call the component’s asyncData method to get the data, and the client is used to store the pre-rendered data into our eventBus data. This is equivalent to implementing the functionality of the Vuex class.
146. What are the advantages and disadvantages of SSR and SPA respectively?
A:
SSR:
- Better for SEO.
- Better for first screen rendering
- The server is under heavy pressure
SPA:
- Switching between pages is very fast
- Somewhat less stress on the back-end server (regardless of page logic and rendering)
- The backend application only needs to provide the API, regardless of whether the client is a Web interface or a mobile phone, etc
- Is not conducive to SEO
- The loading pressure of the first screen is large
147. How to handle the problem that Node.js renders HTML too much stress?
A:
Have not encountered slow situation temporarily, cannot answer, give up this question.
148. What CI/CD tools do you know? Have you been exposed to a similar process in the project?
A:
CICD is continuous integration and continuous delivery. When various departments work together on the same project, when various managed warehouses change, the code will be tested and built automatically. After the Pipline runs, the running results will be fed back and the latest master package will be automatically printed.
Commonly used CICD tools include Jenkins, Travis and so on.
149. If you were to implement a CI/CD engineering development platform for a Web front end, how would you design it?
A:
The topic is too big and the space is limited.
150. What is your solution if we need to convert online production resources (such as pictures) from existing projects to cost private resources?
A:
I don’t know if this question wants to ask me how to collect the existing online resources from the local material center, or simply change the display resources into local ones. For example, there is an el-Table in a page, 5000 pages, 20 items per page, you do not know the link of each item, the URL after each item is not regular, at this time for developers, you know is the page node, interface API these two key information. If you want to rearrange the 20*5000 commodity details map to the local material center, write a crawler and crawl all the resource paths down at once. Or write a chrome plugin for one-click collection.
If you simply want to replace the static resources in your production environment with the local ones, go directly to the static resources link of your application, find its baseUrl, and replace it with the baseUrl in the local dev environment. General project static resources and server services are developed separately, both independent, separate push. And each release, static resources have their own version number.
151. How to customize a scaffold using Vue CLI 3.x? Internal automatic integration of i18N, AXIOS, Element UI, routing guard, etc.?
A:
// See the back of the paper
Copy the code
152. How does Jenkins work with node.js scripts for CI/CD design?
A:
// See the back of the paper
Copy the code
153. If you were asked to design a universal project scaffold, how would you design it? What are the typical capabilities required for a universal scaffold?
A:
Refer to vue-cli for at least the following:
- Decoupling: Separation of scaffold from formwork
- Scaffolding is responsible for the construction process and interacts with the user through the command line to obtain project information
- Templates are responsible for unifying the project structure, workflow, and dependency management
- The scaffold detects whether the template version is updated and supports template deletion and creation
154. If you were asked to design a common tool library, how would you design it? What are the typical capabilities of a common tool library?
A:
At least four conditions are met
- Choose generic, appropriate, and convenient build tools that are easy to package code and easy to debug;
- Focus on code quality and development efficiency, with type inference and static checking capabilities (write TS ahead of time);
- The API is simple and easy to use, and the documents are updated in real time;
- Easy for developers to expand, version upgrades to maintain forward compatibility.
155. Suppose you implemented the React or Vue component library to design the demo document. How would you design it? What does the design document need to do?
A:
Document the code before you write it. Undocumented component libraries = white writing. Documentation is not only for users to see, but also for maintainers to give their own products a kind of macro control. The first document to real-time, concise, easy to use; Second to do a good job of version control, whether it is Vue component library, or small program component library, many times to consider the environment restrictions (such as Vue API changes, small program basic library changes), to real-time update and compatibility, encounter incompatible version barriers, special instructions, the appropriate place throw waring; Third, we should support on demand loading and high versatility and expansibility, I ever also was just a component library API call master, now also in the maintenance of their component library, I know that UI library’s biggest problem is not the style is not complete, but others think you are bad to use, in order to use a toast, you want to download the entire component library, do more harm than good, on-demand load is very important, Support for extensions is even more important, making it easier for other developers to patch your component library.
156. How do you design the API documentation when designing the toolkit package?
A:
This is not a problem. Designing and organizing THE API documentation shows the maintainer’s attitude towards the product, and should be done at the time of development, rather than waiting for it to be fully developed. Writing API documentation will also help you review your product functionality from an outsider’s perspective. Specific API documentation can be implemented using vuepress, RAP2, and so on.
157. What is single sign-on? How do I do single sign-on?
A: In single sign-on (SSO) mode, users can log in to multiple application systems on the same account platform only once to access all trusted application systems. For example, you logged in to baidu cloud disk in the web page, then you go to post post is not need to log in twice.
The essence of single sign-on is to share the login status across multiple applications. If the login status of the user is recorded in the Session, to realize the sharing of the login status, the Session should be shared first. For example, the Session can be serialized into Redis, so that multiple application systems can share the same Redis, and the Session can be directly read from Redis.
Because different application systems have different domain names, although sessions are shared, the domain names of different applications in an enterprise are different, and cross-site or cross-domain may still occur.
How to implement the front-end aspects:
- The parent domain Cookie
- Certification center
- LocalStorage cross-domain
158. How to internationalize a project?
A:
There are two types of methods,
I. Define the locale in the project code through i18 and other plug-ins, and provide the translation function of static and dynamic copywriting through common language translation functions. Main idea is through the build tools to complete style, image replacement, such as the class attribute of the replacement work, won’t appear too much in the business code for internationalization and more variable names, at the same time using a general translation function to complete the translation work static copywriting and dynamic copy, instead of using different framework provides the internationalization of the corresponding plug-in.
2. Do not use plug-ins in the project, but encapsulate a set of general translation functions, define the locale in the backend service, and call different themes and locales through API services to return different fields and page content. (No Chinese in the project code, all variables wrapped with translation functions)
159. How to do a project monitoring and burial plan?
A:
Monitoring is the practice, burial is the tool, data analysis is the goal. All three have different roles on the same path.
What to monitor? Generally, the data to be monitored by front-end projects can be divided into five categories:
-
The system life cycle data can be used to observe page performance and overall access.
-
HTTP speed measurement data, which can be used to observe external service invocations, page performance optimization, etc.
-
Abnormal system data can be used to observe system stability and abnormal system problems.
-
User behavior data, which can be used to observe page stability, overall access, and so on.
-
User logs are used to troubleshoot problems reported by users.
There are three common front-end burial schemes: code burial, visual burial and non-trace burial. No matter which burial method is used, we need to standardize the data. As the final data needs to be sent to the server for calculation and monitoring, we need to convert the collected data according to the agreed protocol format with the server.
In order to quickly discover and locate problems, we need to report the data and running logs of these buried points to the server, which then converts, stores, calculates and monitors them. Generally, it is reported in the form of a new GIF. At the same time, in order to avoid data reporting too frequently and increase the pressure on the server, we can integrate the data locally, such as maintenance by queue or array, and then choose the following way/time to report.
Say one word, some of the scenes we need to know the user equipment breakdown or abnormal data circumstance, but often not trigger this case buried point, or when the trigger user exit application, so here recommend buried the need to point to upload data offline, is to elevate the buried point queue, put in the cache, spit bubbles slowly, It does not compete for resources with API services in the main business process.
After data is reported, a visual management end is generally needed to monitor the data intuitively. In daily monitoring, we also push monitoring data, alarm thresholds, emails, and robots to relevant personnel to detect and solve problems in a timely manner. For example, if the number of abnormal 5 minutes is greater than the threshold, nail or SMS alarm, let the relevant colleagues to repair the abnormal function in time. If we want to do more, we can even collaborate with other systems, such as associating with the BUG management system, automatically generating the BUG sheet, binding the BUG sheet to the corresponding version branch, automatically reversing the status of the BUG sheet by submitting the corresponding fix branch and testing verification, etc.
160. How to build project stability (monitoring, grayscale, error degradation, rollback…) ?
A:
I have not been a Leader, the following purely from the perspective of teammates answer.
In advance: make reasonable division of labor and schedule, control project risks, learn to test yourself, and don’t leave all risks to test students.
After the event: timely monitor the products released online to observe whether they run normally and meet expectations. If there is a bug or an exception in the online version, the primary goal is to restore services and roll back in time. Do not try to overwrite with the new version.
Recovery: timely find their own problems and improve, to avoid falling into the same pit; Let team members and managers know what they’re doing; Sorting out and sharing project experience, not expect the whole team to grow, at least in this product development cycle to gain.
161. What performance optimization considerations should be taken into account for managing back-office applications in general?
A:
General management background application, basically is Vue+Element, or React+ ANTD such components, and the business is toB, to internal use of this kind, generally SPA, in terms of performance, is not so particular, code optimization:
- The modules are decoupled, and each module is uniformly handled by the framework. The responsibilities of each module are sorted out, the work and functions that each module is responsible for and the boundary and invocation mode of each module are determined.
- Modules are registered as services, and the required services are obtained by declaring dependencies. The framework will analyze the dependencies between modules to determine whether a certain service needs to be initialized or destroyed, so as to avoid unnecessary services being loaded.
- Decompress the common library, decompress the component library, reuse the code, and abstract and encapsulate the components and the common library for the repeated logic. Avoid duplicate copy of a method everywhere; UI libraries are referenced as needed, removing unnecessary code (such as using tree-shaking). Load modules asynchronously, and load modules in multiple steps according to business needs (for example, optimize the DEPENDENCY injection framework to initialize modules in batches).
- Differentiated services, loading only the required module content (such as read/write separation) for different scenarios.
Optimization from the engineering perspective:
- Static resources use the CDN
- The compressed file
- For CRM management platform applications with more charts, consider image optimization, such as Sprite graphs, lazy loading
- HTTP2
- Webpack is used to load the code on demand and extract the code from the third library to reduce the redundancy of ES6 to ES5
SAO operation forbidden zone:
- Don’t ask for a lot of Echart chart data at once on the front page of the dashboard in the background. If the page is not heavily visited, don’t try to automatically redirect to the page after logging in. Unless it is really fast, it will not load.
- Front end do not try to request page 0 100,000th data to try to read all the data of a table, ask the back end to interface, do not own waves, such as page card dead, operation with a small pot pot hit your head.
162. Brief some cases and technical solutions to improve the project experience (skeleton screen, Loading processing, caching, error degradation, request retry…) ?
A:
- Live broadcast activities, large page views of commodity details, page with skeleton screen, loading guide customers to go around other activities when the waiting time is too long, so as not to let users blind, etc.
- For both H5 and small programs, all buried point data should be uploaded offline, all buried point requests in the buried point queue should be put in the cache, and sent slowly one by one and bubble slowly, which not only ensures that the data will not compete with the main process business requests, but also will not be detected because the user’s device exits and the application exits. Because the next time you enter the cache, as long as there are not empty bubble (buried request queue) continue to send.
- Application service HTTP request encapsulates a layer of circuit breaker task queue, add retry mechanism, add token automatic refresh request and so on.
- Applying a page with appropriate slow animation not only buys time to request data, but also makes the user experience less obtuse.
- H5 can use keel animation, spine animation, small program can use frame animation, CSS animation to improve the page dynamic, as well as some interactive marketing effect. Much better implementation and coding than naked DOM writing.
163. Suppose you needed to design a watermarking scheme for a page, how would you design it?
A:
- Use Canvas to generate watermark, use Canvas to generate base64 image, and check compatibility through CanIUse website.
- Watermark is generated through SVG. Compared with Canvas, SVG has better compatibility with browsers. The watermark generated using SVG is similar to that of Canvas, but the generation method of base64Url is changed to SVG.
- The server draws the picture and generates the watermark through NodeJS. The front end sends a request, the parameter takes the watermark content, the background returns the picture content.
164. How to design a generic JSON Schema protocol that can dynamically render a generic linkage form?
A:
// See the back of the paper
Copy the code
165. What capabilities are required for a typical low-code platform?
A:
Alibaba’s imgCook, Cloud Phoenix butterfly, JD.com’s Babel, Mangang’s Ma Liang, Xu Xiaoxi’s H5 Doring and so on, all without exception, at least meet the following abilities:
- Business-oriented software design mode, low code is mainly for operations, through the use of modules or components, to provide operations staff with materials, build their own marketing campaign page.
- It can provide a knowledge base of reusable business components. Components can be combined with each other to form new business components, rather than a single independent basic component, with high reusability and extensibility.
- The process integration ability and data integration ability, which can facilitate the integration with third-party systems, can be embedded into other applications in the form of SDK or NPM package, or other applications can be embedded to support the integration of data.
- The ability to support multiple deployment patterns regardless of the platform itself
- It is highly configurable to meet the requirements of different environments, different scales, and different service scenarios
166. Use TypeScript syntax to convert flat, non-hierarchical data into a tree structure
A:
interfaceConfig { id? :stringpid? :stringchildren? :string
}
Constrcut builds nodes into one or more trees based on the id, PID, and children provided *@param Nodes Node object *@param Config Config object */
export function construct(nodes: object[], config? : Config) {
const id = config && config.id || 'id'
const pid = config && config.pid || 'pid'
const children = config && config.children || 'children'
const idMap = {}
const jsonTree = []
nodes.forEach((v) = > { v && (idMap[v[id]] = v) })
nodes.forEach((v) = > {
if (v) {
let parent = idMap[v[pid]]
if(parent) { ! parent[children] && (parent[children] = []) parent[children].push(v) }else {
jsonTree.push(v)
}
}
})
return jsonTree
}
/** * destruct * divides the destruct tree object into nodes based on the configured ID, PID, and children *@param Forest Single or multiple tree objects *@param * / config configuration
export function destruct(forest: object[] | object, config? : Config) {
const id = config && config.id || 'id'
const pid = config && config.pid || 'pid'
const children = config && config.children || 'children'
function flatTree(tree: object) {
const queue = [tree]
const result = []
while (queue.length) {
let currentNode = queue.shift()
if (currentNode.hasOwnProperty(id)) {
if(! currentNode.hasOwnProperty(pid)) { currentNode = { ... currentNode, [pid]:null}}if (currentNode[children]) {
currentNode[children].forEach((v) = >{ v && queue.push({ ... v, [pid]: currentNode[id] }) }) } result.push(currentNode)delete currentNode[children]
} else {
throw new Error('you need to specify the [id] of the json tree')}}return result
}
if (Array.isArray(forest)) {
return forest.map((v) = > flatTree(v)).reduce((pre, cur) = > pre.concat(cur))
} else {
return flatTree(forest)
}
}
export default {
construct,
destruct,
}
Copy the code
167. Implement a simple template engine
A: The role of the template engine is to convert a template file to another template format tools, engine internal processes is the content in the template file as a string passed to the template engine, then the template engine according to certain grammar to parse the string processing, and then return a function, then we in executive function, go in data transmission, You get a new string based on the template and data.
Template — — — — — — — — > > input to the template engine generating function — — — – > the data as a parameter, to perform this function — — — — > output.
Start implementing a suggestion template engine that satisfies variable definition, interpolation, condition determination, and array traversal.
"use strict";
var __PARSE__ = (function () {
/* Regular syntax */
const regmap = [
// The if statement starts
{
reg: /^if\s+(.+)/i,
val: (all, condition) = > {
return `if(${condition}) {`; }},// The elseif statement starts
{
reg: /^elseif\s+(.+)/i,
val: (all, condition) = > {
return `} else if(${condition}) {`; }},// The else statement ends
{ reg: /^else/i, val: "} else {" },
// The if statement ends
{ reg: /^\/\s*if/i, val: "}" },
// Start the list statement
{
reg: /^list\s+([\S]+)\s+as\s+([\S]+)/i,
val: (all, arr, item) = > {
return `for(var __INDEX__=0; __INDEX__<${arr}.length; __INDEX__++) {var${item}=${arr}[__INDEX__]; var${item}_index=__INDEX__; `; }},// The list statement ends
{ reg: /^\/\s*list/i, val: "}" },
/ / var statement
{
reg: /^var\s+(.+)/i,
val: (all, expr) = > {
return `var ${expr}; `; }},];/** The default filter */
const defaultFilter = {
// Anti-injection
escape: (str) = > {
// Anti-injection transcoding mapping table
var escapeMap = {
"<": "<".">": ">"."&": "&"."": " ".'"': """."'": "& # 39;"."\n": "<br/>"."\r": ""};return str.replace(/\<|\>|\&|\r|\n|\s|\'|\"/g.(one) = > {
returnescapeMap[one]; }); }};/* Convert template statements */
let transStm = function (stmJs) {
stmJs = stmJs.trim();
for (let item of regmap) {
if (item.reg.test(stmJs)) {
return typeof item.val === "function"? stmJs.replace(item.reg, item.val) : item.val; }}};/* Parse template */
let doParseTemplate = function (content, data, filter) {
content = content
.replace(/\t/g."")
.replace(/\n/g."\\n")
.replace(/\r/g."\\r");
// Initialize the template generator structure
let out = [];
let struct = [
"try { var OUT = [];"."".// Place the template generator placeholder
"return OUT.join(''); } catch(e) { throw e; }",];// Initialize the template variables
let vars = [];
Object.keys(data).forEach((name) = > {
vars.push(`var ${name} = DATA['${name}']. `);
});
out.push(vars.join(""));
// Initialize the filter
let filters = ["var FILTERS = {};"];
Object.keys(filter).forEach((name) = > {
if (typeof filter[name] === "function") {
filters.push(`FILTERS['${name}'] = FILTER['${name}']. `); }}); out.push(filters.join(""));
// Parse the template content
let beg = 0; // Parse the starting position of the paragraph
let stmbeg = 0; // Start position of expression
let stmend = 0; // End position of the expression
let len = content.length;
let preCode = ""; // The code before the expression
let endCode = ""; // The last piece of code
let stmJs = ""; / / expression
while (beg < len) {
/* Start character */
stmbeg = content.indexOf("{", beg);
while (content.charAt(stmbeg - 1) = = ="\ \") {
// Encounter escape situation
stmbeg = content.indexOf("{", stmbeg + 1);
}
if (stmbeg === -1) {
// Get to the last piece of code
endCode = content.substr(beg);
out.push("OUT.push('" + endCode + "');");
break;
}
/* End character */
stmend = content.indexOf("}", stmbeg);
while (content.charAt(stmend - 1) = = ="\ \") {
// Encounter escape situation
stmend = content.indexOf("}", stmend + 1);
}
if (stmend === -1) {
// There is no terminator
break;
}
// The code before the start
preCode = content.substring(beg, stmbeg);
if (content.charAt(stmbeg - 1) = = ="$") {
// Value for variables
out.push(`OUT.push(\'${preCode.substr(0, preCode.length - 1)}\ '); `);
stmJs = content.substring(stmbeg + 1, stmend);
// Process the filter
let tmp = "";
stmJs.split("|").forEach((item, index) = > {
if (index === 0) {
// Force transcoding variables
tmp = item;
} else {
/ / filter
let farr = item.split(":");
tmp = `FILTERS['${farr[0]}'] (${tmp}`;
if (farr[1]) {
// Filter with variables
farr[1].split(",").forEach((fitem) = > {
tmp = `${tmp}.${fitem}`;
});
}
tmp = `${tmp}) `; // Append the end}}); out.push(`OUT.push((${tmp}).toString()); `);
} else {
// For js statements
out.push(`OUT.push(\'${preCode}\ '); `);
stmJs = content.substring(stmbeg + 1, stmend);
out.push(transStm(stmJs));
}
beg = stmend + 1;
}
// Merge content
struct[1] = out.join("");
return new Function("DATA"."FILTER", struct.join(""));
};
/** Generate code from template data */
return function (content, data, filter) {
try {
data = data || {};
filter = Object.assign({}, defaultFilter, filter);
// Parse the template to generate a code generator
let f = doParseTemplate(content, data, filter);
return f(data, filter);
} catch (ex) {
return ex.stack;
}
};
})();
if (typeof module! = ="undefined" && typeof exports= = ="object") {
module.exports = __PARSE__;
} else {
window.parse = __PARSE__;
}
Copy the code
168. Simply implement a publish/subscribe pattern
A:
const eventEmitter = {
list: {},
Subscription / * * * /
on(event, fn) {
let _this = this;
(_this.list[event] || (_this.list[event] = [])).push(fn);
return _this;
},
/** Listen once */
once(event, fn) {
// Bind first, call later delete
let _this = this;
function on() {
_this.off(event, on);
fn.apply(_this, arguments);
}
on.fn = fn;
_this.on(event, on);
return _this;
},
Unloading / * * * /
off(event, fn) {
let _this = this;
let fns = _this.list[event];
if(! fns)return false;
if(! fn) { fns && (fns.length =0);
} else {
let cb;
for (let i = 0, cbLen = fns.length; i < cbLen; i++) {
cb = fns[i];
if (cb === fn || cb.fn === fn) {
fns.splice(i, 1);
break; }}}return _this;
},
/** 发布 */
emit() {
let _this = this;
let event = [].shift.call(arguments),
fns = [..._this.list[event]];
if(! fns || fns.length ===0) {
return false;
}
fns.forEach((fn) = > {
fn.apply(_this, arguments);
});
return_this; }};Copy the code
= const a = require(‘ XXX ‘)
A:
// See the back of the paper
Copy the code
reference
The syllabus is as follows
Basic knowledge mainly includes the following aspects:
-
Basic knowledge: computer principle, compiling principle, data structure, algorithm, design pattern, programming paradigm and other basic knowledge
-
Syntax: Understand and use the syntax of JavaScript, ECMAScript, CSS, TypeScript, HTML, Node.js, etc
-
Framework: React, Vue, Egg, Koa, Express, Webpack and other principles of understanding and use
-
Project: understand and use compilation tools, format tools, Git, NPM, unit testing, Nginx, PM2, CI/CD
-
Network: UNDERSTANDING of HTTP, TCP, UDP, WebSocket, Cookie, Session, cross-domain, cache and protocol
-
Performance: Learn about compilation performance, monitoring, white screen detection, SEO, and Service Worker
-
Plugins: understanding the design ideas of Chrome, Vue CLI, Webpack and other plugins
-
System: Mac, Windows, and Linux system configuration practices
-
Back-end: Redis cache, database, Graphql, SSR, template engine and other understanding and use
Number of volume
Score: _____