今日已更新 344 条资讯 | 累计 37249 条内容
关于我们

From CSS selector to source line: instrumenting Angular templates

Oussama LARIBI 2026年08月23日 14:17 1 次阅读 来源:Dev.to

Every accessibility tool I have used reports violations like this: Images must have alternative text body > main > div:nth-child(2) > form > div.field > img That selector is correct. It is also useless. It describes the rendered DOM , and I do not write rendered DOM — I write templates. Somewhere in a few hundred .component.html files there is an <img> that produced it, and finding it is manual work: grep for img , get forty hits, open them one by one, compare surrounding markup until something matches. Multiply that by sixty violations and the scan stops being useful. Not because it is wrong, but because acting on it costs more than ignoring it. React solved this years ago If you write JSX, babel-plugin-transform-react-jsx-source puts a _debugSource on every element at build time — file, line, column. That is how React DevTools can jump you straight to source, and how error overlays point at the right line. Angular has no equivalent. The compiler knows the position of every element in every template: it has to, to report template errors. But nothing carries that knowledge into the DOM. So I built the bridge. parseTemplate hands you the positions @angular/compiler exports parseTemplate , the same entry point @angular-eslint uses. Give it a template string and you get an AST where every node carries a sourceSpan with byte offsets, lines and columns: import { parseTemplate } from ' @angular/compiler ' ; const parsed = parseTemplate ( source , filePath , { preserveWhitespaces : true }); // each element node has startSourceSpan.start.{offset,line,col} Two things to know immediately. The compiler counts lines and columns from zero , and every editor counts from one — so you add one, or every location you report is off by one in both axes and nobody trusts the tool again: line : span . start . line + 1 , // the compiler counts from zero, editors do not column : span . start . col + 1 , And preserveWhitespaces: true matters: without it the offsets you get back describe a t

本文内容来源于互联网,版权归原作者所有
查看原文