compileScript.spec.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import { compileSFCScript as compile, assertCode, mockId } from './utils'
  3. describe('SFC compile <script setup>', () => {
  4. test('should expose top level declarations', () => {
  5. const { content, bindings } = compile(`
  6. <script setup>
  7. import { x } from './x'
  8. let a = 1
  9. const b = 2
  10. function c() {}
  11. class d {}
  12. </script>
  13. <script>
  14. import { xx } from './x'
  15. let aa = 1
  16. const bb = 2
  17. function cc() {}
  18. class dd {}
  19. </script>
  20. `)
  21. expect(content).toMatch('return { aa, bb, cc, dd, a, b, c, d, xx, x }')
  22. expect(bindings).toStrictEqual({
  23. x: BindingTypes.SETUP_MAYBE_REF,
  24. a: BindingTypes.SETUP_LET,
  25. b: BindingTypes.SETUP_CONST,
  26. c: BindingTypes.SETUP_CONST,
  27. d: BindingTypes.SETUP_CONST,
  28. xx: BindingTypes.SETUP_MAYBE_REF,
  29. aa: BindingTypes.SETUP_LET,
  30. bb: BindingTypes.SETUP_CONST,
  31. cc: BindingTypes.SETUP_CONST,
  32. dd: BindingTypes.SETUP_CONST
  33. })
  34. assertCode(content)
  35. })
  36. test('binding analysis for destructure', () => {
  37. const { content, bindings } = compile(`
  38. <script setup>
  39. const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
  40. </script>
  41. `)
  42. expect(content).toMatch('return { foo, bar, baz, y, z }')
  43. expect(bindings).toStrictEqual({
  44. foo: BindingTypes.SETUP_MAYBE_REF,
  45. bar: BindingTypes.SETUP_MAYBE_REF,
  46. baz: BindingTypes.SETUP_MAYBE_REF,
  47. y: BindingTypes.SETUP_MAYBE_REF,
  48. z: BindingTypes.SETUP_MAYBE_REF
  49. })
  50. assertCode(content)
  51. })
  52. test('defineProps()', () => {
  53. const { content, bindings } = compile(`
  54. <script setup>
  55. const props = defineProps({
  56. foo: String
  57. })
  58. const bar = 1
  59. </script>
  60. `)
  61. // should generate working code
  62. assertCode(content)
  63. // should analyze bindings
  64. expect(bindings).toStrictEqual({
  65. foo: BindingTypes.PROPS,
  66. bar: BindingTypes.SETUP_CONST,
  67. props: BindingTypes.SETUP_REACTIVE_CONST
  68. })
  69. // should remove defineOptions import and call
  70. expect(content).not.toMatch('defineProps')
  71. // should generate correct setup signature
  72. expect(content).toMatch(`setup(__props, { expose }) {`)
  73. // should assign user identifier to it
  74. expect(content).toMatch(`const props = __props`)
  75. // should include context options in default export
  76. expect(content).toMatch(`export default {
  77. props: {
  78. foo: String
  79. },`)
  80. })
  81. test('defineProps w/ external definition', () => {
  82. const { content } = compile(`
  83. <script setup>
  84. import { propsModel } from './props'
  85. const props = defineProps(propsModel)
  86. </script>
  87. `)
  88. assertCode(content)
  89. expect(content).toMatch(`export default {
  90. props: propsModel,`)
  91. })
  92. // #4764
  93. test('defineProps w/ leading code', () => {
  94. const { content } = compile(`
  95. <script setup>import { x } from './x'
  96. const props = defineProps({})
  97. </script>
  98. `)
  99. // props declaration should be inside setup, not moved along with the import
  100. expect(content).not.toMatch(`const props = __props\nimport`)
  101. assertCode(content)
  102. })
  103. test('defineEmits()', () => {
  104. const { content, bindings } = compile(`
  105. <script setup>
  106. const myEmit = defineEmits(['foo', 'bar'])
  107. </script>
  108. `)
  109. assertCode(content)
  110. expect(bindings).toStrictEqual({
  111. myEmit: BindingTypes.SETUP_CONST
  112. })
  113. // should remove defineOptions import and call
  114. expect(content).not.toMatch('defineEmits')
  115. // should generate correct setup signature
  116. expect(content).toMatch(`setup(__props, { expose, emit: myEmit }) {`)
  117. // should include context options in default export
  118. expect(content).toMatch(`export default {
  119. emits: ['foo', 'bar'],`)
  120. })
  121. test('defineProps/defineEmits in multi-variable declaration', () => {
  122. const { content } = compile(`
  123. <script setup>
  124. const props = defineProps(['item']),
  125. a = 1,
  126. emit = defineEmits(['a']);
  127. </script>
  128. `)
  129. assertCode(content)
  130. expect(content).toMatch(`const a = 1;`) // test correct removal
  131. expect(content).toMatch(`props: ['item'],`)
  132. expect(content).toMatch(`emits: ['a'],`)
  133. })
  134. // #6757
  135. test('defineProps/defineEmits in multi-variable declaration fix #6757 ', () => {
  136. const { content } = compile(`
  137. <script setup>
  138. const a = 1,
  139. props = defineProps(['item']),
  140. emit = defineEmits(['a']);
  141. </script>
  142. `)
  143. assertCode(content)
  144. expect(content).toMatch(`const a = 1;`) // test correct removal
  145. expect(content).toMatch(`props: ['item'],`)
  146. expect(content).toMatch(`emits: ['a'],`)
  147. })
  148. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  149. const { content } = compile(`
  150. <script setup>
  151. const props = defineProps(['item']),
  152. emit = defineEmits(['a']);
  153. </script>
  154. `)
  155. assertCode(content)
  156. expect(content).toMatch(`props: ['item'],`)
  157. expect(content).toMatch(`emits: ['a'],`)
  158. })
  159. test('defineExpose()', () => {
  160. const { content } = compile(`
  161. <script setup>
  162. defineExpose({ foo: 123 })
  163. </script>
  164. `)
  165. assertCode(content)
  166. // should remove defineOptions import and call
  167. expect(content).not.toMatch('defineExpose')
  168. // should generate correct setup signature
  169. expect(content).toMatch(`setup(__props, { expose }) {`)
  170. // should replace callee
  171. expect(content).toMatch(/\bexpose\(\{ foo: 123 \}\)/)
  172. })
  173. test('<script> after <script setup> the script content not end with `\\n`', () => {
  174. const { content } = compile(`
  175. <script setup>
  176. import { x } from './x'
  177. </script>
  178. <script>const n = 1</script>
  179. `)
  180. assertCode(content)
  181. })
  182. describe('<script> and <script setup> co-usage', () => {
  183. test('script first', () => {
  184. const { content } = compile(`
  185. <script>
  186. export const n = 1
  187. export default {}
  188. </script>
  189. <script setup>
  190. import { x } from './x'
  191. x()
  192. </script>
  193. `)
  194. assertCode(content)
  195. })
  196. test('script setup first', () => {
  197. const { content } = compile(`
  198. <script setup>
  199. import { x } from './x'
  200. x()
  201. </script>
  202. <script>
  203. export const n = 1
  204. export default {}
  205. </script>
  206. `)
  207. assertCode(content)
  208. })
  209. test('script setup first, named default export', () => {
  210. const { content } = compile(`
  211. <script setup>
  212. import { x } from './x'
  213. x()
  214. </script>
  215. <script>
  216. export const n = 1
  217. const def = {}
  218. export { def as default }
  219. </script>
  220. `)
  221. assertCode(content)
  222. })
  223. // #4395
  224. test('script setup first, lang="ts", script block content export default', () => {
  225. const { content } = compile(`
  226. <script setup lang="ts">
  227. import { x } from './x'
  228. x()
  229. </script>
  230. <script lang="ts">
  231. export default {
  232. name: "test"
  233. }
  234. </script>
  235. `)
  236. // ensure __default__ is declared before used
  237. expect(content).toMatch(/const __default__[\S\s]*\.\.\.__default__/m)
  238. assertCode(content)
  239. })
  240. describe('spaces in ExportDefaultDeclaration node', () => {
  241. // #4371
  242. test('with many spaces and newline', () => {
  243. // #4371
  244. const { content } = compile(`
  245. <script>
  246. export const n = 1
  247. export default
  248. {
  249. some:'option'
  250. }
  251. </script>
  252. <script setup>
  253. import { x } from './x'
  254. x()
  255. </script>
  256. `)
  257. assertCode(content)
  258. })
  259. test('with minimal spaces', () => {
  260. const { content } = compile(`
  261. <script>
  262. export const n = 1
  263. export default{
  264. some:'option'
  265. }
  266. </script>
  267. <script setup>
  268. import { x } from './x'
  269. x()
  270. </script>
  271. `)
  272. assertCode(content)
  273. })
  274. })
  275. })
  276. describe('imports', () => {
  277. test('should hoist and expose imports', () => {
  278. assertCode(
  279. compile(`<script setup>
  280. import { ref } from 'vue'
  281. import 'foo/css'
  282. </script>`).content
  283. )
  284. })
  285. test('should extract comment for import or type declarations', () => {
  286. assertCode(
  287. compile(`
  288. <script setup>
  289. import a from 'a' // comment
  290. import b from 'b'
  291. </script>
  292. `).content
  293. )
  294. })
  295. // #2740
  296. test('should allow defineProps/Emit at the start of imports', () => {
  297. assertCode(
  298. compile(`<script setup>
  299. import { ref } from 'vue'
  300. defineProps(['foo'])
  301. defineEmits(['bar'])
  302. const r = ref(0)
  303. </script>`).content
  304. )
  305. })
  306. test('dedupe between user & helper', () => {
  307. const { content } = compile(
  308. `
  309. <script setup>
  310. import { ref } from 'vue'
  311. let foo = $ref(1)
  312. </script>
  313. `,
  314. { reactivityTransform: true }
  315. )
  316. assertCode(content)
  317. expect(content).toMatch(`import { ref } from 'vue'`)
  318. })
  319. test('import dedupe between <script> and <script setup>', () => {
  320. const { content } = compile(`
  321. <script>
  322. import { x } from './x'
  323. </script>
  324. <script setup>
  325. import { x } from './x'
  326. x()
  327. </script>
  328. `)
  329. assertCode(content)
  330. expect(content.indexOf(`import { x }`)).toEqual(
  331. content.lastIndexOf(`import { x }`)
  332. )
  333. })
  334. })
  335. // in dev mode, declared bindings are returned as an object from setup()
  336. // when using TS, users may import types which should not be returned as
  337. // values, so we need to check import usage in the template to determine
  338. // what to be returned.
  339. describe('dev mode import usage check', () => {
  340. test('components', () => {
  341. const { content } = compile(`
  342. <script setup lang="ts">
  343. import { FooBar, FooBaz, FooQux, foo } from './x'
  344. const fooBar: FooBar = 1
  345. </script>
  346. <template>
  347. <FooBaz></FooBaz>
  348. <foo-qux/>
  349. <foo/>
  350. FooBar
  351. </template>
  352. `)
  353. // FooBar: should not be matched by plain text or incorrect case
  354. // FooBaz: used as PascalCase component
  355. // FooQux: used as kebab-case component
  356. // foo: lowercase component
  357. expect(content).toMatch(`return { fooBar, FooBaz, FooQux, foo }`)
  358. assertCode(content)
  359. })
  360. test('directive', () => {
  361. const { content } = compile(`
  362. <script setup lang="ts">
  363. import { vMyDir } from './x'
  364. </script>
  365. <template>
  366. <div v-my-dir></div>
  367. </template>
  368. `)
  369. expect(content).toMatch(`return { vMyDir }`)
  370. assertCode(content)
  371. })
  372. // https://github.com/vuejs/core/issues/4599
  373. test('attribute expressions', () => {
  374. const { content } = compile(`
  375. <script setup lang="ts">
  376. import { bar, baz } from './x'
  377. const cond = true
  378. </script>
  379. <template>
  380. <div :class="[cond ? '' : bar(), 'default']" :style="baz"></div>
  381. </template>
  382. `)
  383. expect(content).toMatch(`return { cond, bar, baz }`)
  384. assertCode(content)
  385. })
  386. test('vue interpolations', () => {
  387. const { content } = compile(`
  388. <script setup lang="ts">
  389. import { x, y, z, x$y } from './x'
  390. </script>
  391. <template>
  392. <div :id="z + 'y'">{{ x }} {{ yy }} {{ x$y }}</div>
  393. </template>
  394. `)
  395. // x: used in interpolation
  396. // y: should not be matched by {{ yy }} or 'y' in binding exps
  397. // x$y: #4274 should escape special chars when creating Regex
  398. expect(content).toMatch(`return { x, z, x$y }`)
  399. assertCode(content)
  400. })
  401. // #4340 interpolations in template strings
  402. test('js template string interpolations', () => {
  403. const { content } = compile(`
  404. <script setup lang="ts">
  405. import { VAR, VAR2, VAR3 } from './x'
  406. </script>
  407. <template>
  408. {{ \`\${VAR}VAR2\${VAR3}\` }}
  409. </template>
  410. `)
  411. // VAR2 should not be matched
  412. expect(content).toMatch(`return { VAR, VAR3 }`)
  413. assertCode(content)
  414. })
  415. // edge case: last tag in template
  416. test('last tag', () => {
  417. const { content } = compile(`
  418. <script setup lang="ts">
  419. import { FooBaz, Last } from './x'
  420. </script>
  421. <template>
  422. <FooBaz></FooBaz>
  423. <Last/>
  424. </template>
  425. `)
  426. expect(content).toMatch(`return { FooBaz, Last }`)
  427. assertCode(content)
  428. })
  429. test('TS annotations', () => {
  430. const { content } = compile(`
  431. <script setup lang="ts">
  432. import { Foo, Bar, Baz, Qux, Fred } from './x'
  433. const a = 1
  434. function b() {}
  435. </script>
  436. <template>
  437. {{ a as Foo }}
  438. {{ b<Bar>() }}
  439. {{ Baz }}
  440. <Comp v-slot="{ data }: Qux">{{ data }}</Comp>
  441. <div v-for="{ z = x as Qux } in list as Fred"/>
  442. </template>
  443. `)
  444. expect(content).toMatch(`return { a, b, Baz }`)
  445. assertCode(content)
  446. })
  447. // vuejs/vue#12591
  448. test('v-on inline statement', () => {
  449. // should not error
  450. compile(`
  451. <script setup lang="ts">
  452. import { foo } from './foo'
  453. </script>
  454. <template>
  455. <div @click="$emit('update:a');"></div>
  456. </template>
  457. `)
  458. })
  459. })
  460. describe('inlineTemplate mode', () => {
  461. test('should work', () => {
  462. const { content } = compile(
  463. `
  464. <script setup>
  465. import { ref } from 'vue'
  466. const count = ref(0)
  467. </script>
  468. <template>
  469. <div>{{ count }}</div>
  470. <div>static</div>
  471. </template>
  472. `,
  473. { inlineTemplate: true }
  474. )
  475. // check snapshot and make sure helper imports and
  476. // hoists are placed correctly.
  477. assertCode(content)
  478. // in inline mode, no need to call expose() since nothing is exposed
  479. // anyway!
  480. expect(content).not.toMatch(`expose()`)
  481. })
  482. test('with defineExpose()', () => {
  483. const { content } = compile(
  484. `
  485. <script setup>
  486. const count = ref(0)
  487. defineExpose({ count })
  488. </script>
  489. `,
  490. { inlineTemplate: true }
  491. )
  492. assertCode(content)
  493. expect(content).toMatch(`setup(__props, { expose })`)
  494. expect(content).toMatch(`expose({ count })`)
  495. })
  496. test('referencing scope components and directives', () => {
  497. const { content } = compile(
  498. `
  499. <script setup>
  500. import ChildComp from './Child.vue'
  501. import SomeOtherComp from './Other.vue'
  502. import vMyDir from './my-dir'
  503. </script>
  504. <template>
  505. <div v-my-dir></div>
  506. <ChildComp/>
  507. <some-other-comp/>
  508. </template>
  509. `,
  510. { inlineTemplate: true }
  511. )
  512. expect(content).toMatch('[_unref(vMyDir)]')
  513. expect(content).toMatch('_createVNode(ChildComp)')
  514. // kebab-case component support
  515. expect(content).toMatch('_createVNode(SomeOtherComp)')
  516. assertCode(content)
  517. })
  518. test('avoid unref() when necessary', () => {
  519. // function, const, component import
  520. const { content } = compile(
  521. `<script setup>
  522. import { ref } from 'vue'
  523. import Foo, { bar } from './Foo.vue'
  524. import other from './util'
  525. import * as tree from './tree'
  526. const count = ref(0)
  527. const constant = {}
  528. const maybe = foo()
  529. let lett = 1
  530. function fn() {}
  531. </script>
  532. <template>
  533. <Foo>{{ bar }}</Foo>
  534. <div @click="fn">{{ count }} {{ constant }} {{ maybe }} {{ lett }} {{ other }}</div>
  535. {{ tree.foo() }}
  536. </template>
  537. `,
  538. { inlineTemplate: true }
  539. )
  540. // no need to unref vue component import
  541. expect(content).toMatch(`createVNode(Foo,`)
  542. // #2699 should unref named imports from .vue
  543. expect(content).toMatch(`unref(bar)`)
  544. // should unref other imports
  545. expect(content).toMatch(`unref(other)`)
  546. // no need to unref constant literals
  547. expect(content).not.toMatch(`unref(constant)`)
  548. // should directly use .value for known refs
  549. expect(content).toMatch(`count.value`)
  550. // should unref() on const bindings that may be refs
  551. expect(content).toMatch(`unref(maybe)`)
  552. // should unref() on let bindings
  553. expect(content).toMatch(`unref(lett)`)
  554. // no need to unref namespace import (this also preserves tree-shaking)
  555. expect(content).toMatch(`tree.foo()`)
  556. // no need to unref function declarations
  557. expect(content).toMatch(`{ onClick: fn }`)
  558. // no need to mark constant fns in patch flag
  559. expect(content).not.toMatch(`PROPS`)
  560. assertCode(content)
  561. })
  562. test('v-model codegen', () => {
  563. const { content } = compile(
  564. `<script setup>
  565. import { ref } from 'vue'
  566. const count = ref(0)
  567. const maybe = foo()
  568. let lett = 1
  569. </script>
  570. <template>
  571. <input v-model="count">
  572. <input v-model="maybe">
  573. <input v-model="lett">
  574. </template>
  575. `,
  576. { inlineTemplate: true }
  577. )
  578. // known const ref: set value
  579. expect(content).toMatch(`(count).value = $event`)
  580. // const but maybe ref: assign if ref, otherwise do nothing
  581. expect(content).toMatch(`_isRef(maybe) ? (maybe).value = $event : null`)
  582. // let: handle both cases
  583. expect(content).toMatch(
  584. `_isRef(lett) ? (lett).value = $event : lett = $event`
  585. )
  586. assertCode(content)
  587. })
  588. test('template assignment expression codegen', () => {
  589. const { content } = compile(
  590. `<script setup>
  591. import { ref } from 'vue'
  592. const count = ref(0)
  593. const maybe = foo()
  594. let lett = 1
  595. let v = ref(1)
  596. </script>
  597. <template>
  598. <div @click="count = 1"/>
  599. <div @click="maybe = count"/>
  600. <div @click="lett = count"/>
  601. <div @click="v += 1"/>
  602. <div @click="v -= 1"/>
  603. <div @click="() => {
  604. let a = '' + lett
  605. v = a
  606. }"/>
  607. <div @click="() => {
  608. // nested scopes
  609. (()=>{
  610. let x = a
  611. (()=>{
  612. let z = x
  613. let z2 = z
  614. })
  615. let lz = z
  616. })
  617. v = a
  618. }"/>
  619. </template>
  620. `,
  621. { inlineTemplate: true }
  622. )
  623. // known const ref: set value
  624. expect(content).toMatch(`count.value = 1`)
  625. // const but maybe ref: only assign after check
  626. expect(content).toMatch(`maybe.value = count.value`)
  627. // let: handle both cases
  628. expect(content).toMatch(
  629. `_isRef(lett) ? lett.value = count.value : lett = count.value`
  630. )
  631. expect(content).toMatch(`_isRef(v) ? v.value += 1 : v += 1`)
  632. expect(content).toMatch(`_isRef(v) ? v.value -= 1 : v -= 1`)
  633. expect(content).toMatch(`_isRef(v) ? v.value = a : v = a`)
  634. expect(content).toMatch(`_isRef(v) ? v.value = _ctx.a : v = _ctx.a`)
  635. assertCode(content)
  636. })
  637. test('template update expression codegen', () => {
  638. const { content } = compile(
  639. `<script setup>
  640. import { ref } from 'vue'
  641. const count = ref(0)
  642. const maybe = foo()
  643. let lett = 1
  644. </script>
  645. <template>
  646. <div @click="count++"/>
  647. <div @click="--count"/>
  648. <div @click="maybe++"/>
  649. <div @click="--maybe"/>
  650. <div @click="lett++"/>
  651. <div @click="--lett"/>
  652. </template>
  653. `,
  654. { inlineTemplate: true }
  655. )
  656. // known const ref: set value
  657. expect(content).toMatch(`count.value++`)
  658. expect(content).toMatch(`--count.value`)
  659. // const but maybe ref (non-ref case ignored)
  660. expect(content).toMatch(`maybe.value++`)
  661. expect(content).toMatch(`--maybe.value`)
  662. // let: handle both cases
  663. expect(content).toMatch(`_isRef(lett) ? lett.value++ : lett++`)
  664. expect(content).toMatch(`_isRef(lett) ? --lett.value : --lett`)
  665. assertCode(content)
  666. })
  667. test('template destructure assignment codegen', () => {
  668. const { content } = compile(
  669. `<script setup>
  670. import { ref } from 'vue'
  671. const val = {}
  672. const count = ref(0)
  673. const maybe = foo()
  674. let lett = 1
  675. </script>
  676. <template>
  677. <div @click="({ count } = val)"/>
  678. <div @click="[maybe] = val"/>
  679. <div @click="({ lett } = val)"/>
  680. </template>
  681. `,
  682. { inlineTemplate: true }
  683. )
  684. // known const ref: set value
  685. expect(content).toMatch(`({ count: count.value } = val)`)
  686. // const but maybe ref (non-ref case ignored)
  687. expect(content).toMatch(`[maybe.value] = val`)
  688. // let: assumes non-ref
  689. expect(content).toMatch(`{ lett: lett } = val`)
  690. assertCode(content)
  691. })
  692. test('ssr codegen', () => {
  693. const { content } = compile(
  694. `
  695. <script setup>
  696. import { ref } from 'vue'
  697. const count = ref(0)
  698. </script>
  699. <template>
  700. <div>{{ count }}</div>
  701. <div>static</div>
  702. </template>
  703. <style>
  704. div { color: v-bind(count) }
  705. </style>
  706. `,
  707. {
  708. inlineTemplate: true,
  709. templateOptions: {
  710. ssr: true
  711. }
  712. }
  713. )
  714. expect(content).toMatch(`\n __ssrInlineRender: true,\n`)
  715. expect(content).toMatch(`return (_ctx, _push`)
  716. expect(content).toMatch(`ssrInterpolate`)
  717. expect(content).not.toMatch(`useCssVars`)
  718. expect(content).toMatch(`"--${mockId}-count": (count.value)`)
  719. assertCode(content)
  720. })
  721. })
  722. describe('with TypeScript', () => {
  723. test('hoist type declarations', () => {
  724. const { content } = compile(`
  725. <script setup lang="ts">
  726. export interface Foo {}
  727. type Bar = {}
  728. </script>`)
  729. assertCode(content)
  730. })
  731. test('defineProps/Emit w/ runtime options', () => {
  732. const { content } = compile(`
  733. <script setup lang="ts">
  734. const props = defineProps({ foo: String })
  735. const emit = defineEmits(['a', 'b'])
  736. </script>
  737. `)
  738. assertCode(content)
  739. expect(content).toMatch(`export default /*#__PURE__*/_defineComponent({
  740. props: { foo: String },
  741. emits: ['a', 'b'],
  742. setup(__props, { expose, emit }) {`)
  743. })
  744. test('defineProps w/ type', () => {
  745. const { content, bindings } = compile(`
  746. <script setup lang="ts">
  747. interface Test {}
  748. type Alias = number[]
  749. defineProps<{
  750. string: string
  751. number: number
  752. boolean: boolean
  753. object: object
  754. objectLiteral: { a: number }
  755. fn: (n: number) => void
  756. functionRef: Function
  757. objectRef: Object
  758. dateTime: Date
  759. array: string[]
  760. arrayRef: Array<any>
  761. tuple: [number, number]
  762. set: Set<string>
  763. literal: 'foo'
  764. optional?: any
  765. recordRef: Record<string, null>
  766. interface: Test
  767. alias: Alias
  768. method(): void
  769. symbol: symbol
  770. union: string | number
  771. literalUnion: 'foo' | 'bar'
  772. literalUnionNumber: 1 | 2 | 3 | 4 | 5
  773. literalUnionMixed: 'foo' | 1 | boolean
  774. intersection: Test & {}
  775. foo: ((item: any) => boolean) | null
  776. }>()
  777. </script>`)
  778. assertCode(content)
  779. expect(content).toMatch(`string: { type: String, required: true }`)
  780. expect(content).toMatch(`number: { type: Number, required: true }`)
  781. expect(content).toMatch(`boolean: { type: Boolean, required: true }`)
  782. expect(content).toMatch(`object: { type: Object, required: true }`)
  783. expect(content).toMatch(`objectLiteral: { type: Object, required: true }`)
  784. expect(content).toMatch(`fn: { type: Function, required: true }`)
  785. expect(content).toMatch(`functionRef: { type: Function, required: true }`)
  786. expect(content).toMatch(`objectRef: { type: Object, required: true }`)
  787. expect(content).toMatch(`dateTime: { type: Date, required: true }`)
  788. expect(content).toMatch(`array: { type: Array, required: true }`)
  789. expect(content).toMatch(`arrayRef: { type: Array, required: true }`)
  790. expect(content).toMatch(`tuple: { type: Array, required: true }`)
  791. expect(content).toMatch(`set: { type: Set, required: true }`)
  792. expect(content).toMatch(`literal: { type: String, required: true }`)
  793. expect(content).toMatch(`optional: { type: null, required: false }`)
  794. expect(content).toMatch(`recordRef: { type: Object, required: true }`)
  795. expect(content).toMatch(`interface: { type: Object, required: true }`)
  796. expect(content).toMatch(`alias: { type: Array, required: true }`)
  797. expect(content).toMatch(`method: { type: Function, required: true }`)
  798. expect(content).toMatch(`symbol: { type: Symbol, required: true }`)
  799. expect(content).toMatch(
  800. `union: { type: [String, Number], required: true }`
  801. )
  802. expect(content).toMatch(`literalUnion: { type: String, required: true }`)
  803. expect(content).toMatch(
  804. `literalUnionNumber: { type: Number, required: true }`
  805. )
  806. expect(content).toMatch(
  807. `literalUnionMixed: { type: [String, Number, Boolean], required: true }`
  808. )
  809. expect(content).toMatch(`intersection: { type: Object, required: true }`)
  810. expect(content).toMatch(`foo: { type: [Function, null], required: true }`)
  811. expect(bindings).toStrictEqual({
  812. string: BindingTypes.PROPS,
  813. number: BindingTypes.PROPS,
  814. boolean: BindingTypes.PROPS,
  815. object: BindingTypes.PROPS,
  816. objectLiteral: BindingTypes.PROPS,
  817. fn: BindingTypes.PROPS,
  818. functionRef: BindingTypes.PROPS,
  819. objectRef: BindingTypes.PROPS,
  820. dateTime: BindingTypes.PROPS,
  821. array: BindingTypes.PROPS,
  822. arrayRef: BindingTypes.PROPS,
  823. tuple: BindingTypes.PROPS,
  824. set: BindingTypes.PROPS,
  825. literal: BindingTypes.PROPS,
  826. optional: BindingTypes.PROPS,
  827. recordRef: BindingTypes.PROPS,
  828. interface: BindingTypes.PROPS,
  829. alias: BindingTypes.PROPS,
  830. method: BindingTypes.PROPS,
  831. symbol: BindingTypes.PROPS,
  832. union: BindingTypes.PROPS,
  833. literalUnion: BindingTypes.PROPS,
  834. literalUnionNumber: BindingTypes.PROPS,
  835. literalUnionMixed: BindingTypes.PROPS,
  836. intersection: BindingTypes.PROPS,
  837. foo: BindingTypes.PROPS
  838. })
  839. })
  840. test('defineProps w/ interface', () => {
  841. const { content, bindings } = compile(`
  842. <script setup lang="ts">
  843. interface Props { x?: number }
  844. defineProps<Props>()
  845. </script>
  846. `)
  847. assertCode(content)
  848. expect(content).toMatch(`x: { type: Number, required: false }`)
  849. expect(bindings).toStrictEqual({
  850. x: BindingTypes.PROPS
  851. })
  852. })
  853. test('defineProps w/ extends interface', () => {
  854. const { content, bindings } = compile(`
  855. <script lang="ts">
  856. interface Foo { x?: number }
  857. </script>
  858. <script setup lang="ts">
  859. interface Bar extends Foo { y?: number }
  860. interface Props extends Bar {
  861. z: number
  862. y: string
  863. }
  864. defineProps<Props>()
  865. </script>
  866. `)
  867. assertCode(content)
  868. expect(content).toMatch(`z: { type: Number, required: true }`)
  869. expect(content).toMatch(`y: { type: String, required: true }`)
  870. expect(content).toMatch(`x: { type: Number, required: false }`)
  871. expect(bindings).toStrictEqual({
  872. x: BindingTypes.PROPS,
  873. y: BindingTypes.PROPS,
  874. z: BindingTypes.PROPS
  875. })
  876. })
  877. test('defineProps w/ exported interface', () => {
  878. const { content, bindings } = compile(`
  879. <script setup lang="ts">
  880. export interface Props { x?: number }
  881. defineProps<Props>()
  882. </script>
  883. `)
  884. assertCode(content)
  885. expect(content).toMatch(`x: { type: Number, required: false }`)
  886. expect(bindings).toStrictEqual({
  887. x: BindingTypes.PROPS
  888. })
  889. })
  890. test('defineProps w/ exported interface in normal script', () => {
  891. const { content, bindings } = compile(`
  892. <script lang="ts">
  893. export interface Props { x?: number }
  894. </script>
  895. <script setup lang="ts">
  896. defineProps<Props>()
  897. </script>
  898. `)
  899. assertCode(content)
  900. expect(content).toMatch(`x: { type: Number, required: false }`)
  901. expect(bindings).toStrictEqual({
  902. x: BindingTypes.PROPS
  903. })
  904. })
  905. test('defineProps w/ type alias', () => {
  906. const { content, bindings } = compile(`
  907. <script setup lang="ts">
  908. type Props = { x?: number }
  909. defineProps<Props>()
  910. </script>
  911. `)
  912. assertCode(content)
  913. expect(content).toMatch(`x: { type: Number, required: false }`)
  914. expect(bindings).toStrictEqual({
  915. x: BindingTypes.PROPS
  916. })
  917. })
  918. test('defineProps w/ exported type alias', () => {
  919. const { content, bindings } = compile(`
  920. <script setup lang="ts">
  921. export type Props = { x?: number }
  922. defineProps<Props>()
  923. </script>
  924. `)
  925. assertCode(content)
  926. expect(content).toMatch(`x: { type: Number, required: false }`)
  927. expect(bindings).toStrictEqual({
  928. x: BindingTypes.PROPS
  929. })
  930. })
  931. test('withDefaults (static)', () => {
  932. const { content, bindings } = compile(`
  933. <script setup lang="ts">
  934. const props = withDefaults(defineProps<{
  935. foo?: string
  936. bar?: number;
  937. baz: boolean;
  938. qux?(): number
  939. }>(), {
  940. foo: 'hi',
  941. qux() { return 1 }
  942. })
  943. </script>
  944. `)
  945. assertCode(content)
  946. expect(content).toMatch(
  947. `foo: { type: String, required: false, default: 'hi' }`
  948. )
  949. expect(content).toMatch(`bar: { type: Number, required: false }`)
  950. expect(content).toMatch(`baz: { type: Boolean, required: true }`)
  951. expect(content).toMatch(
  952. `qux: { type: Function, required: false, default() { return 1 } }`
  953. )
  954. expect(content).toMatch(
  955. `{ foo: string, bar?: number, baz: boolean, qux(): number }`
  956. )
  957. expect(content).toMatch(`const props = __props`)
  958. expect(bindings).toStrictEqual({
  959. foo: BindingTypes.PROPS,
  960. bar: BindingTypes.PROPS,
  961. baz: BindingTypes.PROPS,
  962. qux: BindingTypes.PROPS,
  963. props: BindingTypes.SETUP_CONST
  964. })
  965. })
  966. test('withDefaults (dynamic)', () => {
  967. const { content } = compile(`
  968. <script setup lang="ts">
  969. import { defaults } from './foo'
  970. const props = withDefaults(defineProps<{
  971. foo?: string
  972. bar?: number
  973. baz: boolean
  974. }>(), { ...defaults })
  975. </script>
  976. `)
  977. assertCode(content)
  978. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  979. expect(content).toMatch(
  980. `
  981. _mergeDefaults({
  982. foo: { type: String, required: false },
  983. bar: { type: Number, required: false },
  984. baz: { type: Boolean, required: true }
  985. }, { ...defaults })`.trim()
  986. )
  987. })
  988. test('defineEmits w/ type', () => {
  989. const { content } = compile(`
  990. <script setup lang="ts">
  991. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  992. </script>
  993. `)
  994. assertCode(content)
  995. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  996. expect(content).toMatch(`emits: ["foo", "bar"]`)
  997. })
  998. test('defineEmits w/ type (union)', () => {
  999. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  1000. expect(() =>
  1001. compile(`
  1002. <script setup lang="ts">
  1003. const emit = defineEmits<${type}>()
  1004. </script>
  1005. `)
  1006. ).toThrow()
  1007. })
  1008. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  1009. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  1010. const { content } = compile(`
  1011. <script setup lang="ts">
  1012. const emit = defineEmits<${type}>()
  1013. </script>
  1014. `)
  1015. assertCode(content)
  1016. expect(content).toMatch(`emit: (${type}),`)
  1017. expect(content).toMatch(`emits: ["foo", "bar", "baz"]`)
  1018. })
  1019. test('defineEmits w/ type (interface)', () => {
  1020. const { content } = compile(`
  1021. <script setup lang="ts">
  1022. interface Emits { (e: 'foo' | 'bar'): void }
  1023. const emit = defineEmits<Emits>()
  1024. </script>
  1025. `)
  1026. assertCode(content)
  1027. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1028. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1029. })
  1030. test('defineEmits w/ type (exported interface)', () => {
  1031. const { content } = compile(`
  1032. <script setup lang="ts">
  1033. export interface Emits { (e: 'foo' | 'bar'): void }
  1034. const emit = defineEmits<Emits>()
  1035. </script>
  1036. `)
  1037. assertCode(content)
  1038. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1039. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1040. })
  1041. test('defineEmits w/ type (type alias)', () => {
  1042. const { content } = compile(`
  1043. <script setup lang="ts">
  1044. type Emits = { (e: 'foo' | 'bar'): void }
  1045. const emit = defineEmits<Emits>()
  1046. </script>
  1047. `)
  1048. assertCode(content)
  1049. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1050. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1051. })
  1052. test('defineEmits w/ type (exported type alias)', () => {
  1053. const { content } = compile(`
  1054. <script setup lang="ts">
  1055. export type Emits = { (e: 'foo' | 'bar'): void }
  1056. const emit = defineEmits<Emits>()
  1057. </script>
  1058. `)
  1059. assertCode(content)
  1060. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1061. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1062. })
  1063. test('defineEmits w/ type (referenced function type)', () => {
  1064. const { content } = compile(`
  1065. <script setup lang="ts">
  1066. type Emits = (e: 'foo' | 'bar') => void
  1067. const emit = defineEmits<Emits>()
  1068. </script>
  1069. `)
  1070. assertCode(content)
  1071. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1072. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1073. })
  1074. test('defineEmits w/ type (referenced exported function type)', () => {
  1075. const { content } = compile(`
  1076. <script setup lang="ts">
  1077. export type Emits = (e: 'foo' | 'bar') => void
  1078. const emit = defineEmits<Emits>()
  1079. </script>
  1080. `)
  1081. assertCode(content)
  1082. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1083. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1084. })
  1085. // #5393
  1086. test('defineEmits w/ type (interface ts type)', () => {
  1087. const { content } = compile(`
  1088. <script setup lang="ts">
  1089. interface Emits { (e: 'foo'): void }
  1090. const emit: Emits = defineEmits(['foo'])
  1091. </script>
  1092. `)
  1093. assertCode(content)
  1094. expect(content).toMatch(`setup(__props, { expose, emit }) {`)
  1095. expect(content).toMatch(`emits: ['foo']`)
  1096. })
  1097. test('runtime Enum', () => {
  1098. const { content, bindings } = compile(
  1099. `<script setup lang="ts">
  1100. enum Foo { A = 123 }
  1101. </script>`
  1102. )
  1103. assertCode(content)
  1104. expect(bindings).toStrictEqual({
  1105. Foo: BindingTypes.SETUP_CONST
  1106. })
  1107. })
  1108. test('runtime Enum in normal script', () => {
  1109. const { content, bindings } = compile(
  1110. `<script lang="ts">
  1111. export enum D { D = "D" }
  1112. const enum C { C = "C" }
  1113. enum B { B = "B" }
  1114. </script>
  1115. <script setup lang="ts">
  1116. enum Foo { A = 123 }
  1117. </script>`
  1118. )
  1119. assertCode(content)
  1120. expect(bindings).toStrictEqual({
  1121. D: BindingTypes.SETUP_CONST,
  1122. C: BindingTypes.SETUP_CONST,
  1123. B: BindingTypes.SETUP_CONST,
  1124. Foo: BindingTypes.SETUP_CONST
  1125. })
  1126. })
  1127. test('const Enum', () => {
  1128. const { content, bindings } = compile(
  1129. `<script setup lang="ts">
  1130. const enum Foo { A = 123 }
  1131. </script>`
  1132. )
  1133. assertCode(content)
  1134. expect(bindings).toStrictEqual({
  1135. Foo: BindingTypes.SETUP_CONST
  1136. })
  1137. })
  1138. test('import type', () => {
  1139. const { content } = compile(
  1140. `<script setup lang="ts">
  1141. import type { Foo } from './main.ts'
  1142. import { type Bar, Baz } from './main.ts'
  1143. </script>`
  1144. )
  1145. expect(content).toMatch(`return { Baz }`)
  1146. assertCode(content)
  1147. })
  1148. })
  1149. describe('async/await detection', () => {
  1150. function assertAwaitDetection(code: string, shouldAsync = true) {
  1151. const { content } = compile(`<script setup>${code}</script>`, {
  1152. reactivityTransform: true
  1153. })
  1154. if (shouldAsync) {
  1155. expect(content).toMatch(`let __temp, __restore`)
  1156. }
  1157. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  1158. assertCode(content)
  1159. return content
  1160. }
  1161. test('expression statement', () => {
  1162. assertAwaitDetection(`await foo`)
  1163. })
  1164. test('variable', () => {
  1165. assertAwaitDetection(`const a = 1 + (await foo)`)
  1166. })
  1167. test('ref', () => {
  1168. assertAwaitDetection(`let a = $ref(1 + (await foo))`)
  1169. })
  1170. // #4448
  1171. test('nested await', () => {
  1172. assertAwaitDetection(`await (await foo)`)
  1173. assertAwaitDetection(`await ((await foo))`)
  1174. assertAwaitDetection(`await (await (await foo))`)
  1175. })
  1176. // should prepend semicolon
  1177. test('nested leading await in expression statement', () => {
  1178. const code = assertAwaitDetection(`foo()\nawait 1 + await 2`)
  1179. expect(code).toMatch(`foo()\n;(`)
  1180. })
  1181. // #4596 should NOT prepend semicolon
  1182. test('single line conditions', () => {
  1183. const code = assertAwaitDetection(`if (false) await foo()`)
  1184. expect(code).not.toMatch(`if (false) ;(`)
  1185. })
  1186. test('nested statements', () => {
  1187. assertAwaitDetection(`if (ok) { await foo } else { await bar }`)
  1188. })
  1189. test('multiple `if` nested statements', () => {
  1190. assertAwaitDetection(`if (ok) {
  1191. let a = 'foo'
  1192. await 0 + await 1
  1193. await 2
  1194. } else if (a) {
  1195. await 10
  1196. if (b) {
  1197. await 0 + await 1
  1198. } else {
  1199. let a = 'foo'
  1200. await 2
  1201. }
  1202. if (b) {
  1203. await 3
  1204. await 4
  1205. }
  1206. } else {
  1207. await 5
  1208. }`)
  1209. })
  1210. test('multiple `if while` nested statements', () => {
  1211. assertAwaitDetection(`if (ok) {
  1212. while (d) {
  1213. await 5
  1214. }
  1215. while (d) {
  1216. await 5
  1217. await 6
  1218. if (c) {
  1219. let f = 10
  1220. 10 + await 7
  1221. } else {
  1222. await 8
  1223. await 9
  1224. }
  1225. }
  1226. }`)
  1227. })
  1228. test('multiple `if for` nested statements', () => {
  1229. assertAwaitDetection(`if (ok) {
  1230. for (let a of [1,2,3]) {
  1231. await a
  1232. }
  1233. for (let a of [1,2,3]) {
  1234. await a
  1235. await a
  1236. }
  1237. }`)
  1238. })
  1239. test('should ignore await inside functions', () => {
  1240. // function declaration
  1241. assertAwaitDetection(`async function foo() { await bar }`, false)
  1242. // function expression
  1243. assertAwaitDetection(`const foo = async () => { await bar }`, false)
  1244. // object method
  1245. assertAwaitDetection(`const obj = { async method() { await bar }}`, false)
  1246. // class method
  1247. assertAwaitDetection(
  1248. `const cls = class Foo { async method() { await bar }}`,
  1249. false
  1250. )
  1251. })
  1252. })
  1253. describe('errors', () => {
  1254. test('<script> and <script setup> must have same lang', () => {
  1255. expect(() =>
  1256. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1257. ).toThrow(`<script> and <script setup> must have the same language type`)
  1258. })
  1259. const moduleErrorMsg = `cannot contain ES module exports`
  1260. test('non-type named exports', () => {
  1261. expect(() =>
  1262. compile(`<script setup>
  1263. export const a = 1
  1264. </script>`)
  1265. ).toThrow(moduleErrorMsg)
  1266. expect(() =>
  1267. compile(`<script setup>
  1268. export * from './foo'
  1269. </script>`)
  1270. ).toThrow(moduleErrorMsg)
  1271. expect(() =>
  1272. compile(`<script setup>
  1273. const bar = 1
  1274. export { bar as default }
  1275. </script>`)
  1276. ).toThrow(moduleErrorMsg)
  1277. })
  1278. test('defineProps/Emit() w/ both type and non-type args', () => {
  1279. expect(() => {
  1280. compile(`<script setup lang="ts">
  1281. defineProps<{}>({})
  1282. </script>`)
  1283. }).toThrow(`cannot accept both type and non-type arguments`)
  1284. expect(() => {
  1285. compile(`<script setup lang="ts">
  1286. defineEmits<{}>({})
  1287. </script>`)
  1288. }).toThrow(`cannot accept both type and non-type arguments`)
  1289. })
  1290. test('defineProps/Emit() referencing local var', () => {
  1291. expect(() =>
  1292. compile(`<script setup>
  1293. const bar = 1
  1294. defineProps({
  1295. foo: {
  1296. default: () => bar
  1297. }
  1298. })
  1299. </script>`)
  1300. ).toThrow(`cannot reference locally declared variables`)
  1301. expect(() =>
  1302. compile(`<script setup>
  1303. const bar = 'hello'
  1304. defineEmits([bar])
  1305. </script>`)
  1306. ).toThrow(`cannot reference locally declared variables`)
  1307. // #4644
  1308. expect(() =>
  1309. compile(`
  1310. <script>const bar = 1</script>
  1311. <script setup>
  1312. defineProps({
  1313. foo: {
  1314. default: () => bar
  1315. }
  1316. })
  1317. </script>`)
  1318. ).not.toThrow(`cannot reference locally declared variables`)
  1319. })
  1320. test('should allow defineProps/Emit() referencing scope var', () => {
  1321. assertCode(
  1322. compile(`<script setup>
  1323. const bar = 1
  1324. defineProps({
  1325. foo: {
  1326. default: bar => bar + 1
  1327. }
  1328. })
  1329. defineEmits({
  1330. foo: bar => bar > 1
  1331. })
  1332. </script>`).content
  1333. )
  1334. })
  1335. test('should allow defineProps/Emit() referencing imported binding', () => {
  1336. assertCode(
  1337. compile(`<script setup>
  1338. import { bar } from './bar'
  1339. defineProps({
  1340. foo: {
  1341. default: () => bar
  1342. }
  1343. })
  1344. defineEmits({
  1345. foo: () => bar > 1
  1346. })
  1347. </script>`).content
  1348. )
  1349. })
  1350. })
  1351. })
  1352. describe('SFC analyze <script> bindings', () => {
  1353. it('can parse decorators syntax in typescript block', () => {
  1354. const { scriptAst } = compile(`
  1355. <script lang="ts">
  1356. import { Options, Vue } from 'vue-class-component';
  1357. @Options({
  1358. components: {
  1359. HelloWorld,
  1360. },
  1361. props: ['foo', 'bar']
  1362. })
  1363. export default class Home extends Vue {}
  1364. </script>
  1365. `)
  1366. expect(scriptAst).toBeDefined()
  1367. })
  1368. it('recognizes props array declaration', () => {
  1369. const { bindings } = compile(`
  1370. <script>
  1371. export default {
  1372. props: ['foo', 'bar']
  1373. }
  1374. </script>
  1375. `)
  1376. expect(bindings).toStrictEqual({
  1377. foo: BindingTypes.PROPS,
  1378. bar: BindingTypes.PROPS
  1379. })
  1380. expect(bindings!.__isScriptSetup).toBe(false)
  1381. })
  1382. it('recognizes props object declaration', () => {
  1383. const { bindings } = compile(`
  1384. <script>
  1385. export default {
  1386. props: {
  1387. foo: String,
  1388. bar: {
  1389. type: String,
  1390. },
  1391. baz: null,
  1392. qux: [String, Number]
  1393. }
  1394. }
  1395. </script>
  1396. `)
  1397. expect(bindings).toStrictEqual({
  1398. foo: BindingTypes.PROPS,
  1399. bar: BindingTypes.PROPS,
  1400. baz: BindingTypes.PROPS,
  1401. qux: BindingTypes.PROPS
  1402. })
  1403. expect(bindings!.__isScriptSetup).toBe(false)
  1404. })
  1405. it('recognizes setup return', () => {
  1406. const { bindings } = compile(`
  1407. <script>
  1408. const bar = 2
  1409. export default {
  1410. setup() {
  1411. return {
  1412. foo: 1,
  1413. bar
  1414. }
  1415. }
  1416. }
  1417. </script>
  1418. `)
  1419. expect(bindings).toStrictEqual({
  1420. foo: BindingTypes.SETUP_MAYBE_REF,
  1421. bar: BindingTypes.SETUP_MAYBE_REF
  1422. })
  1423. expect(bindings!.__isScriptSetup).toBe(false)
  1424. })
  1425. it('recognizes exported vars', () => {
  1426. const { bindings } = compile(`
  1427. <script>
  1428. export const foo = 2
  1429. </script>
  1430. <script setup>
  1431. console.log(foo)
  1432. </script>
  1433. `)
  1434. expect(bindings).toStrictEqual({
  1435. foo: BindingTypes.SETUP_CONST
  1436. })
  1437. })
  1438. it('recognizes async setup return', () => {
  1439. const { bindings } = compile(`
  1440. <script>
  1441. const bar = 2
  1442. export default {
  1443. async setup() {
  1444. return {
  1445. foo: 1,
  1446. bar
  1447. }
  1448. }
  1449. }
  1450. </script>
  1451. `)
  1452. expect(bindings).toStrictEqual({
  1453. foo: BindingTypes.SETUP_MAYBE_REF,
  1454. bar: BindingTypes.SETUP_MAYBE_REF
  1455. })
  1456. expect(bindings!.__isScriptSetup).toBe(false)
  1457. })
  1458. it('recognizes data return', () => {
  1459. const { bindings } = compile(`
  1460. <script>
  1461. const bar = 2
  1462. export default {
  1463. data() {
  1464. return {
  1465. foo: null,
  1466. bar
  1467. }
  1468. }
  1469. }
  1470. </script>
  1471. `)
  1472. expect(bindings).toStrictEqual({
  1473. foo: BindingTypes.DATA,
  1474. bar: BindingTypes.DATA
  1475. })
  1476. })
  1477. it('recognizes methods', () => {
  1478. const { bindings } = compile(`
  1479. <script>
  1480. export default {
  1481. methods: {
  1482. foo() {}
  1483. }
  1484. }
  1485. </script>
  1486. `)
  1487. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1488. })
  1489. it('recognizes computeds', () => {
  1490. const { bindings } = compile(`
  1491. <script>
  1492. export default {
  1493. computed: {
  1494. foo() {},
  1495. bar: {
  1496. get() {},
  1497. set() {},
  1498. }
  1499. }
  1500. }
  1501. </script>
  1502. `)
  1503. expect(bindings).toStrictEqual({
  1504. foo: BindingTypes.OPTIONS,
  1505. bar: BindingTypes.OPTIONS
  1506. })
  1507. })
  1508. it('recognizes injections array declaration', () => {
  1509. const { bindings } = compile(`
  1510. <script>
  1511. export default {
  1512. inject: ['foo', 'bar']
  1513. }
  1514. </script>
  1515. `)
  1516. expect(bindings).toStrictEqual({
  1517. foo: BindingTypes.OPTIONS,
  1518. bar: BindingTypes.OPTIONS
  1519. })
  1520. })
  1521. it('recognizes injections object declaration', () => {
  1522. const { bindings } = compile(`
  1523. <script>
  1524. export default {
  1525. inject: {
  1526. foo: {},
  1527. bar: {},
  1528. }
  1529. }
  1530. </script>
  1531. `)
  1532. expect(bindings).toStrictEqual({
  1533. foo: BindingTypes.OPTIONS,
  1534. bar: BindingTypes.OPTIONS
  1535. })
  1536. })
  1537. it('works for mixed bindings', () => {
  1538. const { bindings } = compile(`
  1539. <script>
  1540. export default {
  1541. inject: ['foo'],
  1542. props: {
  1543. bar: String,
  1544. },
  1545. setup() {
  1546. return {
  1547. baz: null,
  1548. }
  1549. },
  1550. data() {
  1551. return {
  1552. qux: null
  1553. }
  1554. },
  1555. methods: {
  1556. quux() {}
  1557. },
  1558. computed: {
  1559. quuz() {}
  1560. }
  1561. }
  1562. </script>
  1563. `)
  1564. expect(bindings).toStrictEqual({
  1565. foo: BindingTypes.OPTIONS,
  1566. bar: BindingTypes.PROPS,
  1567. baz: BindingTypes.SETUP_MAYBE_REF,
  1568. qux: BindingTypes.DATA,
  1569. quux: BindingTypes.OPTIONS,
  1570. quuz: BindingTypes.OPTIONS
  1571. })
  1572. })
  1573. it('works for script setup', () => {
  1574. const { bindings } = compile(`
  1575. <script setup>
  1576. import { ref as r } from 'vue'
  1577. defineProps({
  1578. foo: String
  1579. })
  1580. const a = r(1)
  1581. let b = 2
  1582. const c = 3
  1583. const { d } = someFoo()
  1584. let { e } = someBar()
  1585. </script>
  1586. `)
  1587. expect(bindings).toStrictEqual({
  1588. r: BindingTypes.SETUP_CONST,
  1589. a: BindingTypes.SETUP_REF,
  1590. b: BindingTypes.SETUP_LET,
  1591. c: BindingTypes.SETUP_CONST,
  1592. d: BindingTypes.SETUP_MAYBE_REF,
  1593. e: BindingTypes.SETUP_LET,
  1594. foo: BindingTypes.PROPS
  1595. })
  1596. })
  1597. describe('auto name inference', () => {
  1598. test('basic', () => {
  1599. const { content } = compile(
  1600. `<script setup>const a = 1</script>
  1601. <template>{{ a }}</template>`,
  1602. undefined,
  1603. {
  1604. filename: 'FooBar.vue'
  1605. }
  1606. )
  1607. expect(content).toMatch(`export default {
  1608. __name: 'FooBar'`)
  1609. assertCode(content)
  1610. })
  1611. test('do not overwrite manual name (object)', () => {
  1612. const { content } = compile(
  1613. `<script>
  1614. export default {
  1615. name: 'Baz'
  1616. }
  1617. </script>
  1618. <script setup>const a = 1</script>
  1619. <template>{{ a }}</template>`,
  1620. undefined,
  1621. {
  1622. filename: 'FooBar.vue'
  1623. }
  1624. )
  1625. expect(content).not.toMatch(`name: 'FooBar'`)
  1626. expect(content).toMatch(`name: 'Baz'`)
  1627. assertCode(content)
  1628. })
  1629. test('do not overwrite manual name (call)', () => {
  1630. const { content } = compile(
  1631. `<script>
  1632. import { defineComponent } from 'vue'
  1633. export default defineComponent({
  1634. name: 'Baz'
  1635. })
  1636. </script>
  1637. <script setup>const a = 1</script>
  1638. <template>{{ a }}</template>`,
  1639. undefined,
  1640. {
  1641. filename: 'FooBar.vue'
  1642. }
  1643. )
  1644. expect(content).not.toMatch(`name: 'FooBar'`)
  1645. expect(content).toMatch(`name: 'Baz'`)
  1646. assertCode(content)
  1647. })
  1648. })
  1649. })