Skip to content

Commit

Permalink
fix(withastro#5922): improve top-level return error (withastro#6036)
Browse files Browse the repository at this point in the history
Co-authored-by: Nate Moore <[email protected]>
  • Loading branch information
natemoo-re and natemoo-re committed Jan 30, 2023
1 parent fbb34e1 commit e779c62
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/neat-actors-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Improve error handling when top-level `return` is present
11 changes: 9 additions & 2 deletions packages/astro/src/vite-plugin-astro/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ async function enhanceCompileError({
source,
config,
logging,
}: EnhanceCompilerErrorOptions): Promise<never> {
}: EnhanceCompilerErrorOptions): Promise<void> {
const lineText = (err as any).loc?.lineText;
// Verify frontmatter: a common reason that this plugin fails is that
// the user provided invalid JS/TS in the component frontmatter.
// If the frontmatter is invalid, the `err` object may be a compiler
Expand All @@ -104,8 +105,14 @@ async function enhanceCompileError({
// If frontmatter is valid or cannot be parsed, then continue.
const scannedFrontmatter = FRONTMATTER_PARSE_REGEXP.exec(source);
if (scannedFrontmatter) {
// Top-level return is not supported, so replace `return` with throw
const frontmatter = scannedFrontmatter[1].replace(/\breturn\b/g, 'throw');

// If frontmatter does not actually include the offending line, skip
if (lineText && !frontmatter.includes(lineText)) throw err;

try {
await transformWithEsbuild(scannedFrontmatter[1], id, {
await transformWithEsbuild(frontmatter, id, {
loader: 'ts',
target: 'esnext',
sourcemap: false,
Expand Down

0 comments on commit e779c62

Please sign in to comment.