How to deprecate jQuery.once in your Drupal Theme
In order to prevent calls to jquery.once(), we will use the static code analysis tool Eslint
and the Abstract Syntax Tree (AST).
Every frontend developer should be able to configure linters for CSS (Stylelint), or for JS (Eslint). Or at least plug in and extend existing configuration sets, such as eslint-config-airbnb-base
.
Abstract Syntax Tree
The JavaScript
interpreter turns plain program text into a data structure called the Abstract Syntax Tree
before execution.
Eslint
uses abstract syntax trees to check the validity of the syntax constructions in the process of static code analysis.
How does this work?
In the rules
section of the Eslint
configuration file, we can define custom rules to forbid any syntax constructions using the Abstract Syntax Tree.
To achieve this, we have the no-restricted-syntax
key. You can use it to prohibit JavaScript constructions, for example calling setTimeout()
with one argument, calling jQuery.once()
etc. At the same time you can write a custom error message for developers.
You can use Abstract Syntax Tree visualizer to create selectors in Eslint
.
Here we have a classic call to jQuery.once
:
const $menu = $('.menu-label)', context)
$menu.once('menuLabels').each((_, label) => {
label.closest('.menu-item').classList.add('menu-item--label')
})
Clicking on .once
in the left window gives us the corresponding branch of the syntax tree in the right window.
In our case the selector is: MemberExpression[property.name = 'once']
.
Let's write this to the rule in .eslintrc.json
:
{
"rules": {
"no-restricted-syntax": [
"error",
{
"selector": "MemberExpression[property.name = 'once']",
"message": "jQuery once is not allowed. Use native Drupal once implementation."
}
]
}
}
As a result, we get an error in Eslint with the corresponding error.
This way we can forbid any syntax constructions in Eslint.
References: