This video is available to students only

Creating rules for code

Implement a linting rule to prevent the code we just transformed from being reintroduced in the future

The Flash codebase now uses Button components. To get to this point, we first performed an audit of the codebase to understand how button elements were being used today. Then, we created a Button component that was capable of handling all those use cases. Finally, we performed a codemod to transform all of the button elements to the Button component.

This completes the original refactor described in Module 3. However, an actual codebase will continue to evolve and have further changes made. How do we ensure the codebase stays up-to-date using the Button component where appropriate?

A common approach for this is to create a rule for that codebase that enforces this. Any time a change is made, the codebase can be checked against that rule. If there are any violations, the change can be blocked.

For example, in a git workflow, a change is made in a branch off the main branch. Before that branch can be merged, this rule (in addition to other things like tests) need to pass. This way, the main branch should never violate this rule.

This concept of applying rules to code is commonly referred to as linting.

Creating a rule#

Let's start by creating a new linter directory and adding the necessary dependencies.

Then, create a new rule.ts file with much of the same initial setup as the previous custom audit script.

Since all the nodes that matched these criteria were transformed in the previous module, no nodes will match these criteria in the codebase.

To test this, a new violation can intentionally be added to verify it works as expected. Update the LandingPage component in the Flash codebase (or any other component) with the following snippet anywhere in the component.

Now there is a violation, the linting rule can be updated to log the file and line that violates this rule, to make it easy to find and fix. Each node contains a loc property that is an object with information about the starting and ending lines and the column numbers.

When using AST Explorer, make sure Hide location data is disabled for this module. It will otherwise hide all of the loc properties from the tree view.

This location information can be appended to the filename to make it easier to jump directly to the position in the code that the violation occurs.

Now, let's run the script with the known violation.


This page is a preview of Practical Abstract Syntax Trees

Start a new discussion. All notification go to the author.