]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(compiler-sfc): handle more edge cases in default rewrite
authorEvan You <yyx990803@gmail.com>
Fri, 26 Feb 2021 16:05:20 +0000 (11:05 -0500)
committerEvan You <yyx990803@gmail.com>
Fri, 26 Feb 2021 16:05:20 +0000 (11:05 -0500)
packages/compiler-sfc/__tests__/rewriteDefault.spec.ts
packages/compiler-sfc/src/rewriteDefault.ts

index 8bce2ab88c09a3416006dcb105f872f8c8f7f5e4..a6b45e128ad4f722faf5dd85a9b89feeddd854b5 100644 (file)
@@ -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 {}"
+    `)
+  })
 })
index 6dc52fe4bf41107fd93d7cbf63dfcc27b5ea7190..417c70c3aab4cd185f8c2ae7ca290c3b5ec99e7f 100644 (file)
@@ -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
@@ -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
   }