background

The AST is very useful.

This afternoon, I listened to the AST shared by an elder brother in the group.

In order to deepen the impression, wrote a summary, incidentally to share to everyone, hope to give friends some inspiration.

AST useful, mouth said without proof, and see a few specific cases.

Not to mention:

  1. Vue => React
  2. React => Vue

Code conversion method,

Let’s look at a tool that can painlessly upgrade the old React version:

react-codemod

Code address: github.com/reactjs/rea…

This tool, which is very powerful and easy to use, simply requires a single command:

npx react-codemod <transform> <path> [...options]
Copy the code

All with the help of the AST.

So let’s get into today’s content.

The body of the

The main contents of this paper include:

  • 1. Theory: AST concept
  • Practice: Using AST to implement a code conversion tool, putvarConverted tolet
  • Practice: Use AST to implement an Eslint plugin that disables console
  • Practice: Use AST to implement a Babel plug-in and filter Debugger

1. Basic concepts of AST

What is the AST

AST is a hierarchical program representation that presents source code structure according to the grammar of a programming language, each AST node corresponds to an item of a source code.

In computer science, abstract syntax and abstract syntax tree are actually tree-like representations of the abstract syntax structure of source code.

The commonly used browser is through the JS code into an abstract syntax tree for the next step of analysis and other operations.

Therefore, the transformation of JS into an abstract syntax tree is more conducive to the analysis of the program.

What can an AST do

  • Check the code syntax
  • Code style checks
  • Code formatting
  • Highlighting of code
  • Code error
  • Code auto-completion
  • And so on.

AST SanBanFu

  • Generate AST
  • Iterate over and update the AST
  • Regenerate the AST source code

To make it easier to understand, let’s look at a concrete example.

Here is a very useful website by the way: Astexplorer.net/

You are such as:

Declarations, variables, types, all kinds of information.

There are also various plugin templates for you to choose from:

Very convenient.

So let’s do a little practice based on this example.

2. Practice: Use AST to implement a code conversion tool to convert var into let

For example, if you were refactoring an old project and you wanted to replace all var’s in the project with lets, what would you do?

Manual replacement? Or one click with the tool?

Here’s a trick for you: one-click substitution.

First, a killer: Jscodeshift

Jscodeshift is a Javscript Codemod tool.

Codemod is a tool/library to assist you with large-scale codebase refactors that can be partially automated but still require human oversight and occasional intervention.

Jscodeshift is also based on Esprima and easily traverses node over AST via path.

Now let’s replace the VAR in the project.

First, write the code in astExplorer.net.

Template we choose: Jscodeshift

To reverse the name of the variable:

Now we’re going to change the amount, and the nice thing about this tool is that you can highlight the real-time contrast,

Now, find the kind === var object and replace it with let:

We get the following code:

export default function transformer(file, api) {
  const j = api.jscodeshift;

  return j(file.source)
    .find(j.VariableDeclaration, { kind: 'var'})
    .forEach(path= > {
      const letStatement = j.variableDeclaration('let', path.node.declarations)
      j(path).replaceWith(letStatement)
    })
    .toSource();
}
Copy the code

This also works:

path.node.kind = 'let'; // What is passed in is actually a reference
Copy the code

Actual effect:

And we’re done!

Let’s say I have several files in my project that need to do the same:

Simple installation:

sudo npm install -g jscodeshift

Perform:

jscodeshift -t transform.js ./src/demo.js –dry –print

I used –dry and –print

Dry does not immediately overwrite the source file with newly generated code

–print it

In a real project, you would need to operate in separate branches. After the generated code, you would need to review it before merging it.

3. Implement an Eslint plugin using AST to disable console

Similarly, we can make an ESLint plugin that does the same thing: it detects errors when using console.

Desired results:

// Do not use console methods (at 1:9)
   console.log('haha')
/ / -- -- -- -- -- -- -- - ^
Copy the code

We choose the Babel-esLint template this time.

Code implementation:

const disallowMethods = ["log"."info"."warn"."error"."dir"];
export default function(context) {
  return {
    Identifier(node) {
      const isConsoleMethod =
        disallowMethods.includes(node.name) &&
        node.parent.type === "MemberExpression" &&
        node.parent.object.name === "console";

      if(! isConsoleMethod)return;

      context.report({
        node,
        message: "Do not use console methods"}); }}; }Copy the code

Actual effect:

Simple and effective.

But if you have to do something fancy, like define a log, you don’t have to.

Finally, you can encapsulate this code into a complete plug-in:

How to write Eslint plugins

You can practice it yourself.

4. Use AST to implement a Babel plug-in and filter debugger

The last one is to filter the debugger in the source code, Transform we choose Babelv7

With this plugin, we expect to achieve the following effects:

var a = 1
debugger
function test() {
  debugger
   a++
}
debugger
Copy the code

To:

var a = 1;

function test() {
  a++;
}
Copy the code

This is also a very useful feature.

Code implementation:

export default function (babel) {
    const {
        types: t
    } = babel;

    return {
        name: "ast-transform".// not required
        visitor: {
            DebuggerStatement(path) {
                path.remove()
            }
        }
    };
}

Copy the code

Actual effect:

conclusion

That’s about it. It’s not difficult. It’s about theory and introduction.

For those of you who are not familiar with AST, I hope this helps you.

In the future, THERE will be the application of AST in our actual projects, and I will also write a practical article. Please look forward to it!

The above.

read

www.toptal.com/javascript/…

The last

If you feel content is helpful, you can pay attention to my public number “front-end E advanced”, learn together.

clipboard.png