Skip to Content
idomatic 1.6 adds SwiftUI, Flutter and Jetpack Compose. See what changed

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-primary are fragile and break when styles change
  • Debugging - Finding elements in DevTools is harder without meaningful identifiers
  • Accessibility - Labels need for attributes 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 @idomatic

This command will:

  1. Ask you which framework or template language you’re using
  2. Create a .idomatic.config.json configuration file
  3. Install @idomatic/core and the matching parser

Manual Installation

If you prefer manual setup:

npm install -D @idomatic/core

Then create .idomatic.config.json in your project root.


Quick Start

1. Initialize

npm init @idomatic

2. Preview Changes (Dry Run)

npx idomatic scan --dry

This shows which files would be modified without actually changing them.

3. Apply Changes

npx idomatic scan --write

This 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 --write

Options:

FlagDescription
--dryPreview changes without modifying files
--writeApply 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 --dry

This 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

OptionTypeDefaultDescription
attributeNamestring"id"Attribute to inject (id, data-testid, data-cy, etc.)
idStrategystring"semantic""semantic" for readable ids (button-submit) or "random" for ${prefix}${uuid}
prefixstring""Optional string prepended to every id (e.g. "qa-")
includeExtensionsstring[]["js", "jsx", "ts", "tsx"]File extensions to scan
excludeFilesstring[]["node_modules"]Directories or files to ignore (supports glob patterns)
excludeTagsstring[]["html", "head"]HTML tags that should be skipped (in SwiftUI, view names such as "Text")
includeTagsstring[][]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 languageFilesSetup choice
React, Preact, Next.js.jsx .tsx .js .tsReact (JS/TSX)
React Native.jsx .tsxReact Native (writes testID)
SwiftUI.swiftSwiftUI (writes .accessibilityIdentifier)
Flutter.dartFlutter (writes key: const Key(…))
Jetpack Compose.ktJetpack Compose (writes Modifier.testTag)
SolidJS.jsx .tsxSolidJS
Vue.vueHTML / Vue
Svelte.svelteSvelte
Astro.astroAstro
Angular.html .component.tsAngular
Lit / Web Components.js .tsLit / Web Components
Ember.hbs .gjs .gtsHandlebars / Ember
Laravel Blade.blade.phpLaravel Blade
Twig.twigTwig (Symfony)
Django, Jinja, Nunjucks.html .jinja .jinja2 .j2 .njkDjango / Jinja / Nunjucks
Rails ERB, EJS.erb .ejsRuby on Rails (ERB) or EJS
ASP.NET Razor, Blazor.cshtml .razorASP.NET Razor / Blazor
Handlebars, Mustache.hbs .handlebarsHandlebars / Ember
Pug.pugPug
PHP.php .phtmladd "php" to includeExtensions
MDX.mdxMDX
HTML.html .htmHTML / 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, alt or — in JSX/TSX — its text content, falling back to the tag name. Duplicates get a -2, -3 suffix.

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 with includeTags.
  • Not tagged: containers such as VStack, List and Form. 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) becomes textfield-email.
  • Left alone: #Preview and PreviewProvider, anything that already has an identifier, and places where a modifier would change the type and break the build, such as Text("a") + Text("b") or a function that returns Text. Code the Swift grammar can’t read yet, such as typed throws(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, InkWell and CupertinoButton. Add your own widgets with includeTags; they must accept a key.
  • Never duplicated: two siblings with the same key make Flutter throw “Duplicate keys found”. So widgets that one line repeats (for elements, .map(...), List.generate, itemBuilder:) are skipped, and only widgets in build are 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 semanticLabel or tooltip, then the text, labelText/hintText, a label widget, the icon (Icons.delete_outline), the asset name or the controller (_emailController becomes email).
  • key goes first among the named arguments so child stays last, and inside a const expression the const isn’t repeated. Generated files (*.g.dart, *.freezed.dart) and test/ are skipped. Generic widgets such as DropdownButton<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 @Composable functions, such as Button, TextButton, IconButton, FloatingActionButton, TextField, OutlinedTextField, Checkbox, Switch, Slider, Text, Icon, Image, ListItem and NavigationBarItem. Add your own composables with includeTags; they need a modifier parameter.
  • Modifiers: an existing modifier = … gets .testTag("…") at the end. Without one, modifier = Modifier.testTag("…") is added. The Modifier and testTag imports 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 in

After:

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 in

MDX

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-code

idomatic 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-commit

Best 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 --dry

5. Add to CI/CD

Ensure all new code has IDs by adding idomatic to your pipeline.


Troubleshooting

IDs not being added

  1. Check that your file extension is in includeExtensions
  2. Verify the file isn’t in excludeFiles
  3. 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 changes

FAQ

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

Last updated on