navigation

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise

[react] Hooks

[Deployment 01] Nginx [Deployment 02] Docker deployVue project [Deployment 03] gitlab-CI

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] Data reactive and initialize render [source -vue02] Computed responsive – Initialize, access, Update Procedure [source -vue04] Watch Listening properties – Initialize and update [source -vue04] vue. set and vm.$set [source -vue05] vue.extend

Vue. NextTick and VM.$nextTick

Front knowledge

Some words

Abstract syntax tree Identifier: Punctuator: declaration: VariableDeclaration: I'll make this declarator traverse, expression performance //while parseExpression() tries to parse a single Expression with performance inMind. // And parseExpression () tries to parse a single Expression with performance in mindinParse () // If in doubt, use.parse() instead of.parseexpression () Numeric: numberCopy the code

Some websites

Esprima can view tokens generated during the word segmentation stage

There are three stages that go from a javascript program to machine-executable machine code

  • Grammar check: lexical analysis, grammar analysis
  • Compile operation
  • Summary: lexical analysis -> syntax analysis -> compile and run

AST

Abstract syntax tree

AST Application Scenarios

  • Code (syntax detection), Code (style detection), Code (formatting), Code (highlighting), Code (error), Code (autocomplete)
  • eslint amd cmd
  • Webpack escapes JS syntax with Babel

AST analytical process

  • (1) Read (character stream) from js file
  • (2) Generate token through (lexical analysis) ———– Lexical analysis is also called scan scanner, word segmentation stage, token is a one-dimensional array
  • (3) Generate the AST by (parsing) ————- Parsing is also called a parser
  • (4) Generate (machine code) to execute ——————– compilation phase also called compiler

Lexical analysis

  • To convert a char stream into a token stream
  • A token is the smallest indivisible unit and is a one-dimensional array
  • Lexical analysis also called scan
  • Each (keyword, identifier, operator, punctuation, string, number, Boolean, comment, whitespace, space, newline) in (lexical parser) is a token
  • Each object in the token array contains (type) and (value).
  • type
  • value
    • Common (type) are as follows:
    • Keywords:
    • The Identifier of the Identifier
    • Punctuator
    • Numeric
    • String (String)
    • Boolean
    • Null
  • The final code is split into a list of Tokens, a one-dimensional array
1: const add = (a, b) => {return a + b
}

tokens:
[
  { "type": "Keyword"."value": "const" },
  { "type": "Identifier"."value": "add" },
  { "type": "Punctuator"."value": "=" },
  { "type": "Punctuator"."value": "(" },
  { "type": "Identifier"."value": "a" },
  { "type": "Punctuator"."value": "," },
  { "type": "Identifier"."value": "b" },
  { "type": "Punctuator"."value": ")" },
  { "type": "Punctuator"."value": "= >" },
  { "type": "Punctuator"."value": "{" },
  { "type": "Keyword"."value": "return" },
  { "type": "Identifier"."value": "a" },
  { "type": "Punctuator"."value": "+" },
  { "type": "Identifier"."value": "b" },
  { "type": "Punctuator"."value": "}"}} -- source 2: const a = 1; tokens: [ {"type": "Keyword"."value": "const" },
    { "type": "Identifier"."value": "a" },
    { "type": "Punctuator"."value": "=" },
    { "type": "Numeric"."value": "1" },
    { "type": "Punctuator"."value": ";"}] (1) tokenstype(2) Token is the smallest unit of lexical analysis and can no longer be decomposed (3) commontype- keyword Indicates the keyword. - identfier Identifier - Milcher Punctuation - Numeric: numberCopy the code

Syntax analysis

  • (syntax analysis) converts the token obtained by lexical analysis into (syntax meaning) (abstract syntax tree) structure
  • At the same time (validate the syntax), syntax errors are thrown
  • attribute
    • The outermost layer contains:
      • ( type )
      • ( sourceType )
      • ( start )
      • (the end), etc
      • ( body )
        • Body: is an (array) containing multiple (The statement is a content block object), each content block contains
          • type
          • start
          • end
          • kind
          • declarations: times the block that holds the contents of the variable. This block is also an array, since variable declarations can be multiple
            • type
            • start
            • end
            • id
              • type
              • start
              • end
              • name
  • ( An object in the statements-body arrayThere are many types, such as variable declarations, function definitions, if statements, while loops, and so on
    • VariableDeclaration: VariableDeclaration
    • FunctionDeclaration: Function definition
    • IfStatement: indicates an if statement
    • WhileStatement: while loop
Var a = 1; AST {"type": "Program"."start": 0."end": 12."body": [/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the body said code specific content {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the statement piece of content object, a body may contain more than one statement"type": "VariableDeclaration", // --------------------- variable declaration"start": 0."end": 10,
      "declarations": [{"type": "VariableDeclarator", // ------------------ variable declaration"start": 4."end": 9,
          "id": {
            "type": "Identifier", // ------------------------- identifier"start": 4."end": 5,
            "name": "a"
          },
          "init": {
            "type": "Literal"."start": 8,
            "end": 9,
            "value": 1,
            "raw": "1"}}]."kind": "var"/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- variable type}],"sourceType": "module"} (1) outermost attribute:type, start, end, body[],sourceType-body: indicates the specific content of the code - Content block: A body may contain multiple content blocks, each of which is represented by an object - A content block contains: -type- start-end-kind-declarations: multiply the block containing the contents of the variable. This block is also an array, because variable declarations may have multiple -type
            - start
            - end
            - id
                - type
                - start
                - end
                - name 
- source(2) Body is an array of statement block objects, because body can contain more than one statement block. - Statement has many types, such as variable declarations, function definitions,ifStatements,whileLoop, and so on are all a statement -variabledeclaration: VariableDeclaration -functiondeclaration: function definition -ifstatement:ifWhileStatement:whilecycleCopy the code

Babel principle

  • Parse -> transform -> generate
  • Parsing the parse
    • @babel/parser: Converts the string to AST, Babylon(now @babel/parser) is the JavaScript parser used in Babel
    • The parsing process is divided into two stages
      • Syntax analysis: character stream -> Token stream
      • Lexical analysis: Token stream -> AST
    • @babel/parser
  • Transformation transform
    • @babel/traverse: Used to traverse the AST
      • Babel picks up the parsed AST and runs it over babel-traverse.
      • During this traversal, nodes are (added), (updated), and (removed)
      • -Penny: No, I don’t
    • @babel/types: Is used to operate the AST, such as (add), (update) and (remove) operations
      • Instead of manual replacement, @babel/types can be used more quickly
      • Equivalent to the class lodash library for the AST
    • @babel/traverse
    • @babel/types
  • Generate the generate
    • @babel/generator: to convert the converted abstract syntax tree to a Javascript string
      • The converted AST is then converted to JS code via babel-Generator
      • The process iterates through the AST in depth and then builds the transformed code string.
    • @babel/generator

@babel/parser

BabelParser. Parse (code, [options]) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - parse all code babelParser. ParseExpression (code, [options]) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - a single expression parsing parameters: - code: said source string - options: a configuration object, optional - allowImportExportEverywhere: The default import andexportDeclarations can only appear at the top when this option istrueCan appear anywhere -...Copy the code

@babel/traverse

  • Because (@babel/ Parser parsing) and (@babel/generator generating) don’t change much, the point is (@babel/traverse transitions)
import * as babylon from "babylon";
import traverse from "babel-traverse"; String const code = 'function square(n) {
  returnn * n; } `; // Parse: string -> ast const ast = Babylon. Parse (code); Transform: ast -> modified ast traverse(ast, {enter(path) {if (
      path.node.type === "Identifier" &&
      path.node.name === "n"
    ) {
      path.node.name = "x"; // ---------------- if it is an identifier and its name is n, change n to x}}Copy the code

@babel/generator

import {parse} from '@babel/parser';
import generate from '@babel/generator';

const code = 'class Example {}';
const ast = parse(code);

const output = generate(ast, { /* options */ }, code);
Copy the code

Babel conversion code case

  • Requirement: Converts lowercase variables to uppercase
// Enter const numberFive = 5; // Output const NUMBERFIVE = 5;Copy the code
  • The implementation process
Install @ Babel/core -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the Babel core modules @ Babel/parser -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - character stream - > - > token flow AST @ Babel/traverse by -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the AST - > modified AST @ Babel/generator -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- modified AST - flow NPM > characters install @babel/core @babel/parser @babel/traverse @babel/generator -SCopy the code
Const Parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generator = require('@babel/generator').default; Const code = 'const nubmerFive = 5'; / / parsingletAST = parser.parse(code) // Traverse (AST, {enter(path) {console.log(path.node.type,'path.node.type')
    if (path.node.type === 'Identifier') {// If the node type is an identifier, Will name to uppercase path. Node. Name = path. The node. The name. The toUpperCase ()}}}) / / generated const outputObj = the generator (AST) const outputStr  = outputObj.code; console.log(outputStr,'outputStr')
Copy the code

data

AST babel-AST related tools juejin.cn/post/684490… AST from Babel to AST juejin.cn/post/684490… AST segmentfault.com/a/119000001 AST 99% of people don’t understand… AST abstract syntax tree – graphics juejin.cn/post/684490… AST details: segmentfault.com/a/119000001… AST cheogo. Making. IO/learn – javas… AST detailed www.codercto.com/a/88752.htm…

Babel conversion juejin. Cn/post / 684490… Babel cloud.tencent.com/developer/a conversion cases… Babel plug-in introduce zhuanlan.zhihu.com/p/61780633