Skip to content

Commit

Permalink
fix(compiler-sfc): handle more edge cases in default rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Feb 26, 2021
1 parent 012dc5a commit 1dedc19
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
51 changes: 51 additions & 0 deletions packages/compiler-sfc/__tests__/rewriteDefault.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,55 @@ describe('compiler sfc: rewriteDefault', () => {
const script = a"
`)
})

test('w/ comments', async () => {
expect(rewriteDefault(`// export default\nexport default {}`, 'script'))
.toMatchInlineSnapshot(`
"// export default
const script = {}"
`)
})

test('export default class', async () => {
expect(rewriteDefault(`export default class Foo {}`, 'script'))
.toMatchInlineSnapshot(`
"class Foo {}
const script = Foo"
`)
})

test('export default class w/ comments', async () => {
expect(
rewriteDefault(`// export default\nexport default class Foo {}`, 'script')
).toMatchInlineSnapshot(`
"// export default
class Foo {}
const script = Foo"
`)
})

test('export default class w/ comments 2', async () => {
expect(
rewriteDefault(
`export default {}\n` + `// export default class Foo {}`,
'script'
)
).toMatchInlineSnapshot(`
"const script = {}
// export default class Foo {}"
`)
})

test('export default class w/ comments 3', async () => {
expect(
rewriteDefault(
`/*\nexport default class Foo {}*/\n` + `export default class Bar {}`,
'script'
)
).toMatchInlineSnapshot(`
"/*
export default class Foo {}*/
const script = class Bar {}"
`)
})
})
12 changes: 11 additions & 1 deletion packages/compiler-sfc/src/rewriteDefault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import MagicString from 'magic-string'

const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/
const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/
const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/

/**
* Utility for rewriting `export default` in a script block into a variable
Expand All @@ -17,7 +18,16 @@ export function rewriteDefault(
return input + `\nconst ${as} = {}`
}

const replaced = input.replace(defaultExportRE, `$1const ${as} =`)
let replaced: string | undefined

const classMatch = input.match(exportDefaultClassRE)
if (classMatch) {
replaced =
input.replace(exportDefaultClassRE, '$1class $2') +
`\nconst ${as} = ${classMatch[2]}`
} else {
replaced = input.replace(defaultExportRE, `$1const ${as} =`)
}
if (!hasDefaultExport(replaced)) {
return replaced
}
Expand Down

0 comments on commit 1dedc19

Please sign in to comment.