Skip to content

Commit 13ad9fd

Browse files
committed
fix: syntax error tips 🌈
1 parent 53da52c commit 13ad9fd

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

src/minify.ts

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -127,18 +127,15 @@ export class LightningCssMinifyPlugin {
127127
} catch (error: unknown) {
128128
const err = error as Record<string, any>
129129
const fileName = err.fileName || asset.name
130-
const loc = err.loc as
131-
| { line: number; column?: number }
132-
| undefined
130+
const loc = err.loc as { line: number; column?: number } | undefined
133131

134-
const messageParts: string[] = [
135-
`${err.message || error}`,
136-
]
132+
const messageParts: string[] = [`${err.message || error}`]
137133

138134
if (loc && typeof loc.line === 'number') {
139-
const position = typeof loc.column === 'number'
140-
? `${loc.line}:${loc.column}`
141-
: `${loc.line}`
135+
const position =
136+
typeof loc.column === 'number'
137+
? `${loc.line}:${loc.column}`
138+
: `${loc.line}`
142139
messageParts.push(` in ${fileName}:${position}`, '')
143140

144141
const lines = sourceAsString.split('\n')
@@ -153,7 +150,40 @@ export class LightningCssMinifyPlugin {
153150
messageParts.push(` in ${fileName}`)
154151
}
155152

156-
throw new Error(messageParts.join('\n'), { cause: error })
153+
const tipsMessage = []
154+
const errorMessage = messageParts.join('\n')
155+
const maySyntaxError = errorMessage.includes('SyntaxError:')
156+
if (maySyntaxError) {
157+
tipsMessage.push('')
158+
// Tips: `errorRecovery: true`
159+
// https://lightningcss.dev/docs.html#error-recovery
160+
const tipLine = '='.repeat(80)
161+
tipsMessage.push(tipLine)
162+
tipsMessage.push(
163+
`\n[LightningCssMinifyPlugin] This error might be caused by a syntax error in the CSS. \n\nLightningCSS has an 'errorRecovery' option that can be enabled to attempt to recover from syntax errors and provide more detailed error messages. You can enable it in the plugin options:`,
164+
)
165+
tipsMessage.push(`
166+
new LightningCssMinifyPlugin({
167+
// other options...
168+
errorRecovery: true,
169+
})
170+
`)
171+
tipsMessage.push(tipLine)
172+
}
173+
174+
// print tips
175+
console.log()
176+
console.log(tipsMessage.join('\n'))
177+
// print error
178+
console.log()
179+
console.log(`[LightningCssMinifyPlugin] LightningCSS error:`)
180+
console.log(errorMessage)
181+
console.log()
182+
183+
// throw
184+
throw new Error('[LightningCssMinifyPlugin] minification failed', {
185+
cause: error,
186+
})
157187
}
158188
const codeString = result.code.toString()
159189

0 commit comments

Comments
 (0)