Răsfoiți Sursa

fix(compiler-sfc): don't hoist regexp literial (#8300)

三咲智子 Kevin Deng 3 ani în urmă
părinte
comite
8ec73a3aea

+ 2 - 1
packages/compiler-sfc/__tests__/compileScript/__snapshots__/hoistStatic.spec.ts.snap

@@ -37,7 +37,6 @@ exports[`sfc hoist static > should hoist literal value 1`] = `
     const nil = null
     const bigint = 100n
     const template = \`str\`
-    const regex = /.*/g
     
 export default {
   setup(__props) {
@@ -124,6 +123,8 @@ exports[`sfc hoist static > should not hoist a variable 1`] = `
 
     let KEY1 = 'default value'
     var KEY2 = 123
+    const regex = /.*/g
+    const undef = undefined
     
 return () => {}
 }

+ 6 - 4
packages/compiler-sfc/__tests__/compileScript/hoistStatic.spec.ts

@@ -19,7 +19,6 @@ describe('sfc hoist static', () => {
     const nil = null
     const bigint = 100n
     const template = \`str\`
-    const regex = /.*/g
     `.trim()
     const { content, bindings } = compile(`
     <script setup>
@@ -35,8 +34,7 @@ describe('sfc hoist static', () => {
       boolean: BindingTypes.LITERAL_CONST,
       nil: BindingTypes.LITERAL_CONST,
       bigint: BindingTypes.LITERAL_CONST,
-      template: BindingTypes.LITERAL_CONST,
-      regex: BindingTypes.LITERAL_CONST
+      template: BindingTypes.LITERAL_CONST
     })
     assertCode(content)
   })
@@ -90,6 +88,8 @@ describe('sfc hoist static', () => {
     const code = `
     let KEY1 = 'default value'
     var KEY2 = 123
+    const regex = /.*/g
+    const undef = undefined
     `.trim()
     const { content, bindings } = compile(`
     <script setup>
@@ -98,7 +98,9 @@ describe('sfc hoist static', () => {
     `)
     expect(bindings).toStrictEqual({
       KEY1: BindingTypes.SETUP_LET,
-      KEY2: BindingTypes.SETUP_LET
+      KEY2: BindingTypes.SETUP_LET,
+      regex: BindingTypes.SETUP_CONST,
+      undef: BindingTypes.SETUP_MAYBE_REF
     })
     expect(content).toMatch(`setup(__props) {\n\n    ${code}`)
     assertCode(content)

+ 9 - 8
packages/compiler-sfc/src/compileScript.ts

@@ -1247,6 +1247,8 @@ function canNeverBeRef(node: Node, userReactiveImport?: string): boolean {
 }
 
 function isStaticNode(node: Node): boolean {
+  node = unwrapTSNode(node)
+
   switch (node.type) {
     case 'UnaryExpression': // void 0, !true
       return isStaticNode(node.argument)
@@ -1269,15 +1271,14 @@ function isStaticNode(node: Node): boolean {
       return node.expressions.every(expr => isStaticNode(expr))
 
     case 'ParenthesizedExpression': // (1)
-    case 'TSNonNullExpression': // 1!
-    case 'TSAsExpression': // 1 as number
-    case 'TSTypeAssertion': // (<number>2)
       return isStaticNode(node.expression)
 
-    default:
-      if (isLiteralNode(node)) {
-        return true
-      }
-      return false
+    case 'StringLiteral':
+    case 'NumericLiteral':
+    case 'BooleanLiteral':
+    case 'NullLiteral':
+    case 'BigIntLiteral':
+      return true
   }
+  return false
 }