HTML
This page curates a list of example ast-grep rules to check and to rewrite HTML code.
Use HTML parser for frameworks
You can leverage the languageGlobs
option to parse framework files as plain HTML, such as vue
, svelte
, and astro
.
Caveat: This approach may not parse framework-specific syntax, like Astro's frontmatter script or Svelte control flow. You will need to load custom languages for such cases.
Upgrade Ant Design Vue Has Fix
Description
ast-grep can be used to upgrade Vue template using the HTML parser.
This rule is an example to upgrade one breaking change in Ant Design Vue from v3 to v4, unifying the controlled visible API of the component popup.
It is designed to identify and replace the visible
attribute with the open
attribute for specific components like a-modal
and a-tooltip
. Note the rule should not replace other visible attributes that are not related to the component popup like a-tag
.
The rule can be broken down into the following steps:
- Find the target attribute name by
kind
andregex
- Find the attribute's enclosing element using
inside
, and get its tag name - Ensure the tag name is related to popup components, using constraints
YAML
id: upgrade-ant-design-vue
language: HTML
utils:
inside-tag:
# find the enclosing element of the attribute
inside:
kind: element
stopBy: { kind: element } # only the closest element
# find the tag name and store it in metavar
has:
stopBy: { kind: tag_name }
kind: tag_name
pattern: $TAG_NAME
rule:
# find the target attribute_name
kind: attribute_name
regex: :visible
# find the element
matches: inside-tag
# ensure it only matches modal/tooltip but not tag
constraints:
TAG_NAME:
regex: a-modal|a-tooltip
fix: :open
Example
<template>
<a-modal :visible="visible">content</a-modal>
<a-tooltip :visible="visible" />
<a-tag :visible="visible">tag</a-tag>
</template>
Diff
<template>
<a-modal :visible="visible">content</a-modal>
<a-modal :open="visible">content</a-modal>
<a-tooltip :visible="visible" />
<a-tooltip :open="visible" />
<a-tag :visible="visible">tag</a-tag>
</template>
Contributed by
Inspired by Vue.js RFC
Extract i18n Keys Has Fix
Description
It is tedious to manually find and replace all the text in the template with i18n keys. This rule helps to extract static text into i18n keys. Dynamic text, e.g. mustache syntax, will be skipped.
In practice, you may want to map the extracted text to a key in a dictionary file. While this rule only demonstrates the extraction part, further mapping process can be done via a script reading the output of ast-grep's --json
mode, or using @ast-grep/napi
.
YAML
id: extract-i18n-key
language: html
rule:
kind: text
pattern: $T
# skip dynamic text in mustache syntax
not: { regex: '\{\{.*\}\}' }
fix: "{{ $('$T') }}"
Example
<template>
<span>Hello</span>
<span>{{ text }}</span>
</template>
Diff
<template>
<span>Hello</span>
<span>{{ $('Hello') }}</span>
<span>{{ text }}</span>
</template>
Contributed by
Inspired by Vue.js RFC