Skip to content

Commit 02f0668

Browse files
Fallback to js expression parsing for angular directives if needed (#93)
1 parent 4a33bd9 commit 02f0668

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

src/index.js

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,32 @@ function createParser(original, transform) {
188188
}
189189
}
190190

191+
function tryParseAngularAttribute(value, env) {
192+
let parsers = [
193+
// Try parsing as an angular directive
194+
prettierParserAngular.parsers.__ng_directive,
195+
196+
// If this fails we fall back to arbitrary parsing of a JS expression
197+
{ parse: env.parsers.__js_expression },
198+
]
199+
200+
let errors = []
201+
for (const parser of parsers) {
202+
try {
203+
return parser.parse(
204+
value,
205+
env.parsers,
206+
env.options
207+
)
208+
} catch (err) {
209+
errors.push(err)
210+
}
211+
}
212+
213+
console.warn("prettier-plugin-tailwindcss: Unable to parse angular directive")
214+
errors.forEach(err => console.warn(err))
215+
}
216+
191217
function transformHtml(attributes, computedAttributes = [], computedType = 'js') {
192218
let transform = (ast, { env }) => {
193219
for (let attr of ast.attrs ?? []) {
@@ -199,11 +225,15 @@ function transformHtml(attributes, computedAttributes = [], computedType = 'js')
199225
}
200226

201227
if (computedType === 'angular') {
202-
let directiveAst = prettierParserAngular.parsers.__ng_directive.parse(
203-
attr.value,
204-
env.parsers,
205-
env.options
206-
)
228+
let directiveAst = tryParseAngularAttribute(attr.value, env)
229+
230+
// If we've reached this point we couldn't parse the expression we we should bail
231+
// `tryParseAngularAttribute` will display some warnings/errors
232+
// But we shouldn't fail outright — just miss parsing some attributes
233+
if (!directiveAst) {
234+
continue
235+
}
236+
207237
visit(directiveAst, {
208238
StringLiteral(node) {
209239
if (!node.value) return

tests/test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ let tests = {
173173
t`<div [ngClass]="{ '${yes}': true }"></div>`,
174174
t`<div [ngClass]="clsx('${yes}')"></div>`,
175175
t`<div [ngClass]="{ '${yes}': (some.thing | urlPipe: { option: true } | async), '${yes}': true }"></div>`,
176+
t`<div [ngClass]="{ '${yes}': foo && bar?.['baz'] }" class="${yes}"></div>`,
177+
178+
// TODO: Enable this test — it causes console noise but not a failure
179+
// t`<div [ngClass]="{ '${no}': foo && definitely&a:syntax*error }" class="${yes}"></div>`,
176180
],
177181
css: [...css, t`@apply ${yes} !important;`],
178182
scss: [...css, t`@apply ${yes} #{!important};`],

0 commit comments

Comments
 (0)