idomatic
idomatic is a CLI tool that automatically injects id attributes into your components and templates: React, React Native, SwiftUI, Flutter, Jetpack Compose, SolidJS, Vue, Svelte, Astro, Angular, Lit, Ember, Blade, Twig, Django/Jinja, ERB, Razor, Handlebars, Pug, PHP, MDX and plain HTML.
It helps ensure better testability, maintainability, and traceability in your codebase by adding stable, unique id attributes where they’re missing.
Why idomatic?
The Problem
When writing frontend code, developers often forget to add id attributes to elements. This causes problems when:
- Writing E2E tests - Selectors like
.btn-primaryare fragile and break when styles change - Debugging - Finding elements in DevTools is harder without meaningful identifiers
- Accessibility - Labels need
forattributes that reference element IDs - Analytics - Tracking tools need stable identifiers for click tracking
The Solution
idomatic automatically scans your codebase and adds id attributes to elements that don’t have them. It’s:
- Non-destructive - Only adds IDs where missing, never modifies existing ones
- Configurable - Customize prefix, attribute name, excluded tags, and more
- Framework-agnostic - Works with component frameworks, server templates (Blade, Twig, Django, Rails, Razor), SwiftUI, Flutter, Jetpack Compose and MDX. See Framework Guides.
Installation
To install idomatic, run the initializer:
npm init @idomaticThis command will:
- Ask you which framework or template language you’re using
- Create a
.idomatic.config.jsonconfiguration file - Install
@idomatic/coreand the matching parser
Manual Installation
If you prefer manual setup:
npm install -D @idomatic/coreThen create .idomatic.config.json in your project root.
Quick Start
1. Initialize
npm init @idomatic2. Preview Changes (Dry Run)
npx idomatic scan --dryThis shows which files would be modified without actually changing them.
3. Apply Changes
npx idomatic scan --writeThis scans your files and injects missing id attributes.
CLI Commands
idomatic scan
Scans your files and injects missing id attributes based on your config. Pass exactly one flag; with no flag it only prints usage.
npx idomatic scan --writeOptions:
| Flag | Description |
|---|---|
--dry | Preview changes without modifying files |
--write | Apply changes to your files |
idomatic scan --dry
Dry run mode – logs which files would be updated, but doesn’t write anything to disk.
npx idomatic scan --dryThis is useful for:
- CI/CD pipelines to check for missing IDs
- Previewing changes before applying them
- Testing your configuration
Configuration
idomatic uses a .idomatic.config.json config file to customize how and where IDs are applied.
Full Configuration Example
{
"attributeName": "id",
"idStrategy": "semantic",
"prefix": "",
"includeExtensions": ["js", "jsx", "ts", "tsx", "html", "vue"],
"excludeFiles": ["node_modules", "dist", "build", ".next"],
"excludeTags": ["html", "head", "meta", "link", "script", "style", "br", "hr"]
}Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
attributeName | string | "id" | Attribute to inject (id, data-testid, data-cy, etc.) |
idStrategy | string | "semantic" | "semantic" for readable ids (button-submit) or "random" for ${prefix}${uuid} |
prefix | string | "" | Optional string prepended to every id (e.g. "qa-") |
includeExtensions | string[] | ["js", "jsx", "ts", "tsx"] | File extensions to scan |
excludeFiles | string[] | ["node_modules"] | Directories or files to ignore (supports glob patterns) |
excludeTags | string[] | ["html", "head"] | HTML tags that should be skipped (in SwiftUI, view names such as "Text") |
includeTags | string[] | [] | SwiftUI, Flutter and Compose: your own views, widgets or composables to tag as well as the built-in controls |
Configuration Examples
React/JSX Project
{
"prefix": "app-",
"attributeName": "id",
"includeExtensions": ["jsx", "tsx"],
"excludeFiles": ["node_modules", "dist", ".next", "__tests__"],
"excludeTags": ["html", "head", "meta", "link", "script", "style"]
}Vue Project
{
"prefix": "vue-",
"attributeName": "id",
"includeExtensions": ["vue"],
"excludeFiles": ["node_modules", "dist"],
"excludeTags": ["html", "head", "meta", "link", "script", "style", "template"]
}Angular Project
{
"prefix": "ng-",
"attributeName": "id",
"includeExtensions": ["html"],
"excludeFiles": ["node_modules", "dist", "e2e"],
"excludeTags": ["html", "head", "meta", "link", "script", "style", "ng-container", "ng-template"]
}Using data-testid (for Testing)
{
"prefix": "test-",
"attributeName": "data-testid",
"includeExtensions": ["jsx", "tsx"],
"excludeFiles": ["node_modules"],
"excludeTags": ["html", "head", "script", "style"]
}Using data-cy (for Cypress)
{
"prefix": "",
"attributeName": "data-cy",
"includeExtensions": ["jsx", "tsx", "vue"],
"excludeFiles": ["node_modules", "cypress"],
"excludeTags": ["html", "head", "script", "style"]
}Framework Guides
| Framework or language | Files | Setup choice |
|---|---|---|
| React, Preact, Next.js | .jsx .tsx .js .ts | React (JS/TSX) |
| React Native | .jsx .tsx | React Native (writes testID) |
| SwiftUI | .swift | SwiftUI (writes .accessibilityIdentifier) |
| Flutter | .dart | Flutter (writes key: const Key(…)) |
| Jetpack Compose | .kt | Jetpack Compose (writes Modifier.testTag) |
| SolidJS | .jsx .tsx | SolidJS |
| Vue | .vue | HTML / Vue |
| Svelte | .svelte | Svelte |
| Astro | .astro | Astro |
| Angular | .html .component.ts | Angular |
| Lit / Web Components | .js .ts | Lit / Web Components |
| Ember | .hbs .gjs .gts | Handlebars / Ember |
| Laravel Blade | .blade.php | Laravel Blade |
| Twig | .twig | Twig (Symfony) |
| Django, Jinja, Nunjucks | .html .jinja .jinja2 .j2 .njk | Django / Jinja / Nunjucks |
| Rails ERB, EJS | .erb .ejs | Ruby on Rails (ERB) or EJS |
| ASP.NET Razor, Blazor | .cshtml .razor | ASP.NET Razor / Blazor |
| Handlebars, Mustache | .hbs .handlebars | Handlebars / Ember |
| Pug | .pug | Pug |
| PHP | .php .phtml | add "php" to includeExtensions |
| MDX | .mdx | MDX |
| HTML | .html .htm | HTML / Vue |
idomatic only sees what is written in your files, so markup that a helper or component library builds at runtime needs its ids added by hand.
React / JSX / TSX
idomatic works seamlessly with React components:
Before:
function LoginForm() {
return (
<form>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button>Login</button>
</form>
);
}After:
function LoginForm() {
return (
<form id="form">
<input type="email" placeholder="Email" id="input-email" />
<input type="password" placeholder="Password" id="input-password" />
<button id="button-login">Login</button>
</form>
);
}Names are derived from context: an element’s
aria-label,name,placeholder,altor — in JSX/TSX — its text content, falling back to the tag name. Duplicates get a-2,-3suffix.
Vue
idomatic processes Vue Single File Components (.vue files):
Before:
<template>
<form class="search">
<input name="query" placeholder="Search" />
<button aria-label="Run search" @click="handleClick">Go</button>
</form>
</template>After:
<template>
<form class="search" id="form">
<input name="query" placeholder="Search" id="input-query" />
<button aria-label="Run search" @click="handleClick" id="button-run-search">Go</button>
</form>
</template>Angular
For Angular, idomatic processes external HTML template files:
Before (component.html):
<div class="container">
<h1>{{ heading }}</h1>
<input name="search" [(ngModel)]="searchTerm" placeholder="Search...">
<button aria-label="Run search" (click)="onSearch()">Search</button>
</div>After:
<div class="container" id="div">
<h1 id="h1">{{ heading }}</h1>
<input name="search" [(ngModel)]="searchTerm" placeholder="Search..." id="input-search">
<button aria-label="Run search" (click)="onSearch()" id="button-run-search">Search</button>
</div>Inline templates work too. In .component.ts files, the template property of @Component is tagged; control flow such as @if (...) { } is left alone. If the template is a double-quoted string, the new ids use single quotes so the string stays valid. Choose Angular in npm init @idomatic to scan both .html and .component.ts files.
Svelte
idomatic tags the markup in .svelte files. <script> and <style> blocks are left alone, and <svelte:head>, other <svelte:*> elements and <slot> are skipped. Expressions are understood, so a > inside on:click={...} doesn’t confuse it.
Before:
<script>
let count = 0;
</script>
<button aria-label="Increment" on:click={() => count++}>{count}</button>After:
<script>
let count = 0;
</script>
<button aria-label="Increment" on:click={() => count++} id="button-increment">{count}</button>Astro
In .astro files the --- frontmatter is left untouched and only the template is tagged. <Fragment> and <slot> are skipped.
Before:
---
const links = ["docs", "blog"];
---
<nav aria-label="Main">
{links.map((link) => <a href={`/${link}`}>{link}</a>)}
</nav>After:
---
const links = ["docs", "blog"];
---
<nav aria-label="Main" id="nav-main">
{links.map((link) => <a href={`/${link}`} id="a">{link}</a>)}
</nav>An element inside a loop gets a single static id, so every rendered copy shares it. In tests, scope it:
page.locator("#nav-main #a").nth(1). The same applies to.map()in JSX and{{#each}}in Handlebars.
Handlebars / Ember
.hbs and .handlebars templates are supported, including mustaches inside tags. An attribute whose value is an expression, like alt="{{name}}", is never used to build the id name.
Before:
<div class="card" {{#if featured}}data-featured{{/if}}>
<img alt="{{title}}" src="{{cover}}">
<a title="Read more" href="{{url}}">Read</a>
</div>After:
<div class="card" {{#if featured}}data-featured{{/if}} id="div">
<img alt="{{title}}" src="{{cover}}" id="img">
<a title="Read more" href="{{url}}" id="a-read-more">Read</a>
</div>SolidJS
Solid components are JSX, so they go through the same parser as React. Choose SolidJS in npm init @idomatic and the config skips Solid’s control-flow components, which render no DOM node of their own:
{
"includeExtensions": ["jsx", "tsx"],
"excludeTags": ["html", "head", "script", "For", "Index", "Show", "Switch", "Match", "Suspense", "ErrorBoundary", "Portal", "Dynamic"]
}JSX passed through props, such as <Show fallback={<p>Loading</p>}>, is still tagged.
React Native
React Native goes through the JSX parser. Choose React Native in setup and the config writes testID, which Detox, Maestro and React Native Testing Library select by. accessibilityLabel counts as a label, after aria-label.
<Pressable accessibilityLabel="Log in" onPress={submit} testID="pressable-log-in">
<Text testID="text-log-in">Log in</Text>
</Pressable>SwiftUI
Choose SwiftUI in setup. It installs @idomatic/parser-swift, which adds .accessibilityIdentifier("…") to the end of each control’s modifier chain, so XCUITest finds it with app.buttons["button-log-in"]. idomatic runs on Node, so your iOS project gets a package.json; add node_modules/ to .gitignore.
Button("Log in") {
login()
}
.buttonStyle(.borderedProminent)
.accessibilityIdentifier("button-log-in")- Tagged:
Button,Text,TextField,SecureField,TextEditor,Toggle,Picker,Slider,Stepper,DatePicker,ColorPicker,Image,Label,Link,NavigationLink,Menu,ShareLink,ProgressView. Add your own views withincludeTags. - Not tagged: containers such as
VStack,ListandForm. SwiftUI passes a container’s identifier to every child, and tests could no longer tell them apart. Views inside a control’s label are skipped too, because SwiftUI merges them into the control. A Menu’s items and a NavigationLink’s destination are tagged. - Names come from
.accessibilityLabel("…"), then the title (Button("Log in")), a label closure, the system image, or the bound state:TextField("", text: $email)becomestextfield-email. - Left alone:
#PreviewandPreviewProvider, anything that already has an identifier, and places where a modifier would change the type and break the build, such asText("a") + Text("b")or a function that returnsText. Code the Swift grammar can’t read yet, such as typedthrows(MyError), is skipped.
Flutter
Choose Flutter in setup. It installs @idomatic/parser-dart, which gives widgets in build methods a key, so widget and integration tests find them with find.byKey(const Key('elevatedbutton-log-in')).
ElevatedButton(
key: const Key('elevatedbutton-log-in'),
onPressed: _login,
child: const Text('Log in'),
),- Tagged: Material and Cupertino controls such as
ElevatedButton,TextButton,IconButton,TextField,TextFormField,Checkbox,Switch,Slider,ListTile,Text,Icon,Image,InkWellandCupertinoButton. Add your own widgets withincludeTags; they must accept akey. - Never duplicated: two siblings with the same key make Flutter throw “Duplicate keys found”. So widgets that one line repeats (
forelements,.map(...),List.generate,itemBuilder:) are skipped, and only widgets inbuildare keyed, not in helper methods that could be called twice. - Not keyed separately: a control’s label (
child:,title:,icon:). The control has the key. - Names come from
semanticLabelortooltip, then the text,labelText/hintText, a label widget, the icon (Icons.delete_outline), the asset name or the controller (_emailControllerbecomesemail). keygoes first among the named arguments sochildstays last, and inside aconstexpression theconstisn’t repeated. Generated files (*.g.dart,*.freezed.dart) andtest/are skipped. Generic widgets such asDropdownButton<String>(…)aren’t keyed yet.
Jetpack Compose
Choose Jetpack Compose in setup. It installs @idomatic/parser-kotlin, which gives composables a Modifier.testTag, so Compose UI tests find them with onNodeWithTag("button-log-in"). It works the same in Compose Multiplatform.
Button(onClick = onLogin, modifier = Modifier.fillMaxWidth().testTag("button-log-in")) {
Text("Log in")
}- Tagged: controls in
@Composablefunctions, such asButton,TextButton,IconButton,FloatingActionButton,TextField,OutlinedTextField,Checkbox,Switch,Slider,Text,Icon,Image,ListItemandNavigationBarItem. Add your own composables withincludeTags; they need amodifierparameter. - Modifiers: an existing
modifier = …gets.testTag("…")at the end. Without one,modifier = Modifier.testTag("…")is added. TheModifierandtestTagimports are added when missing. - Not tagged separately: a control’s content (
Button { Text("Log in") },label = { … }); Compose merges it into the control. Previews are skipped. - Names come from
contentDescription, then the text,label/placeholder, the content, the icon (Icons.Filled.Delete), the drawable or the bound state (value = email).
Lit / Web Components
Markup in html`...` and svg`...` tagged templates is tagged, including templates nested inside ${...}. Expressions are never touched, and other tagged templates (css`...`, sql`...`) are ignored.
return html`
<ul id="ul">
${this.items.map((i) => html`<li id="li">${i}</li>`)}
</ul>
`;Ember template tags
Besides classic .hbs files, the <template> blocks in .gjs and .gts files are tagged. All blocks in one file share one set of ids, so two components never get the same one. With ember-test-selectors, set "attributeName": "data-test".
Laravel Blade
.blade.php files are tagged with Blade comments ({{-- --}}), @php ... @endphp, inline @php(...) and raw <?php ?> left alone, so a > in PHP never ends a tag. <x-slot> is skipped. Blade components such as <x-button> get an id like any element, so render {{ $attributes }} in the component to pass it through.
Twig
.twig files (including .html.twig) are tagged with {# comments #} skipped. {% if %} and {{ }} inside a tag are fine.
Django, Jinja and Nunjucks
.jinja, .jinja2, .j2 and .njk files are supported. Django templates are usually .html: in an .html file that uses {% %} tags, {# comments #} are skipped too.
Rails ERB and EJS
Everything between <% and %> is left alone, in .erb (including .html.erb) and .ejs files. Markup that a helper such as link_to or form_with builds at runtime isn’t in the file, so pass id: to those helpers yourself.
ASP.NET Razor and Blazor
In .cshtml and .razor files, @* comments *@, @{ } and @code { } blocks, @(...) expressions, @if (...) conditions and directive lines like @model List<Product> are left alone, so C# generics never look like tags. <text> and tag helpers such as <partial> are skipped.
In .razor files, components are skipped unless they pass unknown attributes through (EditForm, InputText, NavLink and the other built-in inputs), because Blazor throws on a parameter a component doesn’t declare.
<h1 id="h1">Counter</h1>
<button class="btn" @onclick="Increment" id="button">Click me</button>
<ProductCard Product="@featured" />Pug
Ids are added as Pug attributes. Multi-line attribute lists and li: a block expansion work, and #id shorthand counts as an existing id. Comments, code lines (-), piped text, mixin calls and the body of text blocks (p., script.) are left alone.
Before:
form.login(method="post")
input(name="email" placeholder="Email")
button.btn(aria-label="Log in") Log inAfter:
form.login(method="post" id="form")
input(name="email" placeholder="Email" id="input-email")
button.btn(aria-label="Log in" id="button-log-in") Log inMDX
JSX elements in .mdx documents are tagged. Frontmatter, fenced and inline code, import/export blocks, JSX comments and <https://...> links are not, so code samples are never mistaken for elements.
PHP
Plain .php and .phtml templates are supported with <?php ?> and <?= ?> blocks left alone. Add "php" to includeExtensions.
Plain HTML
Before:
<section class="hero">
<h1>Welcome</h1>
<p>This is the hero section</p>
<a href="/signup" aria-label="Get started" class="btn">Get Started</a>
</section>After:
<section class="hero" id="section">
<h1 id="h1">Welcome</h1>
<p id="p">This is the hero section</p>
<a href="/signup" aria-label="Get started" class="btn" id="a-get-started">Get Started</a>
</section>CI/CD Integration
GitHub Actions
Add idomatic to your CI pipeline to ensure all new code has proper IDs:
name: Check IDs
on: [push, pull_request]
jobs:
check-ids:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npx idomatic scan --write
- run: git diff --exit-codeidomatic scan itself always exits with 0. To fail the build when an element is missing an id, run it with --write and let git diff --exit-code fail if anything changed.
Pre-commit Hook
Use Husky to run idomatic before each commit:
npm install -D husky
npx husky init
echo "npx idomatic scan" > .husky/pre-commitBest Practices
1. Use Meaningful Prefixes
Choose a prefix that identifies your project or component:
{
"prefix": "myapp-"
}2. Exclude Test Files
Don’t add IDs to test files:
{
"excludeFiles": ["__tests__", "*.test.tsx", "*.spec.ts"]
}3. Use data-testid for Testing
If you’re using Testing Library, use data-testid:
{
"attributeName": "data-testid"
}4. Run Dry Mode First
Always preview changes before applying:
npx idomatic scan --dry5. Add to CI/CD
Ensure all new code has IDs by adding idomatic to your pipeline.
Troubleshooting
IDs not being added
- Check that your file extension is in
includeExtensions - Verify the file isn’t in
excludeFiles - Make sure the tag isn’t in
excludeTags
Existing IDs being overwritten
idomatic never overwrites existing IDs. If you’re seeing this, check if:
- The element truly had an ID before
- You’re looking at the correct file
Config not being read
Make sure .idomatic.config.json is in your project root (same level as package.json).
Package Scripts
Add these scripts to your package.json for convenience:
{
"scripts": {
"ids": "idomatic scan",
"ids:check": "idomatic scan --dry",
"ids:verbose": "idomatic scan --verbose"
}
}Then run:
npm run ids # Apply IDs
npm run ids:check # Preview changesFAQ
Does idomatic modify existing IDs?
No. idomatic only adds IDs to elements that don’t already have one.
Can I use a custom attribute like data-testid?
Yes! Set attributeName in your config:
{
"attributeName": "data-testid"
}Does it work with TypeScript?
Yes. idomatic supports .ts and .tsx files.
Is it safe to run on production code?
Yes. We recommend using --dry first to preview changes. idomatic is non-destructive.
How are IDs generated?
By default (idStrategy: "semantic") ids are derived from each element’s context — aria-label, name, placeholder, alt, text content or tag — and made unique on collision (-2, -3, …). Set idStrategy: "random" to use ${prefix}${uuid} instead.
Support
- GitHub Issues: Report a bug
- GitHub Discussions: Ask a question
- Email: amarsmajlovic27@gmail.com