compileScript.spec.ts 52 KB

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