compileScript.spec.ts 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954
  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 (static) + normal script', () => {
  1063. const { content } = compile(`
  1064. <script lang="ts">
  1065. interface Props {
  1066. a?: string;
  1067. }
  1068. </script>
  1069. <script setup lang="ts">
  1070. const props = withDefaults(defineProps<Props>(), {
  1071. a: "a",
  1072. });
  1073. </script>
  1074. `)
  1075. assertCode(content)
  1076. })
  1077. // #7111
  1078. test('withDefaults (static) w/ production mode', () => {
  1079. const { content } = compile(
  1080. `
  1081. <script setup lang="ts">
  1082. const props = withDefaults(defineProps<{
  1083. foo: () => void
  1084. bar: boolean
  1085. baz: boolean | (() => void)
  1086. qux: string | number
  1087. }>(), {
  1088. baz: true,
  1089. qux: 'hi'
  1090. })
  1091. </script>
  1092. `,
  1093. { isProd: true }
  1094. )
  1095. assertCode(content)
  1096. expect(content).toMatch(`const props = __props`)
  1097. // foo has no default value, the Function can be dropped
  1098. expect(content).toMatch(`foo: null`)
  1099. expect(content).toMatch(`bar: { type: Boolean }`)
  1100. expect(content).toMatch(
  1101. `baz: { type: [Boolean, Function], default: true }`
  1102. )
  1103. expect(content).toMatch(`qux: { default: 'hi' }`)
  1104. })
  1105. test('withDefaults (dynamic)', () => {
  1106. const { content } = compile(`
  1107. <script setup lang="ts">
  1108. import { defaults } from './foo'
  1109. const props = withDefaults(defineProps<{
  1110. foo?: string
  1111. bar?: number
  1112. baz: boolean
  1113. }>(), { ...defaults })
  1114. </script>
  1115. `)
  1116. assertCode(content)
  1117. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1118. expect(content).toMatch(
  1119. `
  1120. _mergeDefaults({
  1121. foo: { type: String, required: false },
  1122. bar: { type: Number, required: false },
  1123. baz: { type: Boolean, required: true }
  1124. }, { ...defaults })`.trim()
  1125. )
  1126. })
  1127. // #7111
  1128. test('withDefaults (dynamic) w/ production mode', () => {
  1129. const { content } = compile(
  1130. `
  1131. <script setup lang="ts">
  1132. import { defaults } from './foo'
  1133. const props = withDefaults(defineProps<{
  1134. foo: () => void
  1135. bar: boolean
  1136. baz: boolean | (() => void)
  1137. qux: string | number
  1138. }>(), { ...defaults })
  1139. </script>
  1140. `,
  1141. { isProd: true }
  1142. )
  1143. assertCode(content)
  1144. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1145. expect(content).toMatch(
  1146. `
  1147. _mergeDefaults({
  1148. foo: { type: Function },
  1149. bar: { type: Boolean },
  1150. baz: { type: [Boolean, Function] },
  1151. qux: null
  1152. }, { ...defaults })`.trim()
  1153. )
  1154. })
  1155. test('defineEmits w/ type', () => {
  1156. const { content } = compile(`
  1157. <script setup lang="ts">
  1158. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  1159. </script>
  1160. `)
  1161. assertCode(content)
  1162. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1163. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1164. })
  1165. test('defineEmits w/ type (union)', () => {
  1166. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  1167. expect(() =>
  1168. compile(`
  1169. <script setup lang="ts">
  1170. const emit = defineEmits<${type}>()
  1171. </script>
  1172. `)
  1173. ).toThrow()
  1174. })
  1175. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  1176. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  1177. const { content } = compile(`
  1178. <script setup lang="ts">
  1179. const emit = defineEmits<${type}>()
  1180. </script>
  1181. `)
  1182. assertCode(content)
  1183. expect(content).toMatch(`emit: (${type}),`)
  1184. expect(content).toMatch(`emits: ["foo", "bar", "baz"]`)
  1185. })
  1186. test('defineEmits w/ type (interface)', () => {
  1187. const { content } = compile(`
  1188. <script setup lang="ts">
  1189. interface Emits { (e: 'foo' | 'bar'): void }
  1190. const emit = defineEmits<Emits>()
  1191. </script>
  1192. `)
  1193. assertCode(content)
  1194. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1195. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1196. })
  1197. test('defineEmits w/ type (exported interface)', () => {
  1198. const { content } = compile(`
  1199. <script setup lang="ts">
  1200. export interface Emits { (e: 'foo' | 'bar'): void }
  1201. const emit = defineEmits<Emits>()
  1202. </script>
  1203. `)
  1204. assertCode(content)
  1205. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1206. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1207. })
  1208. test('defineEmits w/ type from normal script', () => {
  1209. const { content } = compile(`
  1210. <script lang="ts">
  1211. export interface Emits { (e: 'foo' | 'bar'): void }
  1212. </script>
  1213. <script setup lang="ts">
  1214. const emit = defineEmits<Emits>()
  1215. </script>
  1216. `)
  1217. assertCode(content)
  1218. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1219. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1220. })
  1221. test('defineEmits w/ type (type alias)', () => {
  1222. const { content } = compile(`
  1223. <script setup lang="ts">
  1224. type Emits = { (e: 'foo' | 'bar'): void }
  1225. const emit = defineEmits<Emits>()
  1226. </script>
  1227. `)
  1228. assertCode(content)
  1229. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1230. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1231. })
  1232. test('defineEmits w/ type (exported type alias)', () => {
  1233. const { content } = compile(`
  1234. <script setup lang="ts">
  1235. export type Emits = { (e: 'foo' | 'bar'): void }
  1236. const emit = defineEmits<Emits>()
  1237. </script>
  1238. `)
  1239. assertCode(content)
  1240. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1241. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1242. })
  1243. test('defineEmits w/ type (referenced function type)', () => {
  1244. const { content } = compile(`
  1245. <script setup lang="ts">
  1246. type Emits = (e: 'foo' | 'bar') => void
  1247. const emit = defineEmits<Emits>()
  1248. </script>
  1249. `)
  1250. assertCode(content)
  1251. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1252. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1253. })
  1254. test('defineEmits w/ type (referenced exported function type)', () => {
  1255. const { content } = compile(`
  1256. <script setup lang="ts">
  1257. export type Emits = (e: 'foo' | 'bar') => void
  1258. const emit = defineEmits<Emits>()
  1259. </script>
  1260. `)
  1261. assertCode(content)
  1262. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1263. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1264. })
  1265. // #5393
  1266. test('defineEmits w/ type (interface ts type)', () => {
  1267. const { content } = compile(`
  1268. <script setup lang="ts">
  1269. interface Emits { (e: 'foo'): void }
  1270. const emit: Emits = defineEmits(['foo'])
  1271. </script>
  1272. `)
  1273. assertCode(content)
  1274. expect(content).toMatch(`setup(__props, { expose, emit }) {`)
  1275. expect(content).toMatch(`emits: ['foo']`)
  1276. })
  1277. test('runtime Enum', () => {
  1278. const { content, bindings } = compile(
  1279. `<script setup lang="ts">
  1280. enum Foo { A = 123 }
  1281. </script>`
  1282. )
  1283. assertCode(content)
  1284. expect(bindings).toStrictEqual({
  1285. Foo: BindingTypes.SETUP_CONST
  1286. })
  1287. })
  1288. test('runtime Enum in normal script', () => {
  1289. const { content, bindings } = compile(
  1290. `<script lang="ts">
  1291. export enum D { D = "D" }
  1292. const enum C { C = "C" }
  1293. enum B { B = "B" }
  1294. </script>
  1295. <script setup lang="ts">
  1296. enum Foo { A = 123 }
  1297. </script>`
  1298. )
  1299. assertCode(content)
  1300. expect(bindings).toStrictEqual({
  1301. D: BindingTypes.SETUP_CONST,
  1302. C: BindingTypes.SETUP_CONST,
  1303. B: BindingTypes.SETUP_CONST,
  1304. Foo: BindingTypes.SETUP_CONST
  1305. })
  1306. })
  1307. test('const Enum', () => {
  1308. const { content, bindings } = compile(
  1309. `<script setup lang="ts">
  1310. const enum Foo { A = 123 }
  1311. </script>`
  1312. )
  1313. assertCode(content)
  1314. expect(bindings).toStrictEqual({
  1315. Foo: BindingTypes.SETUP_CONST
  1316. })
  1317. })
  1318. test('import type', () => {
  1319. const { content } = compile(
  1320. `<script setup lang="ts">
  1321. import type { Foo } from './main.ts'
  1322. import { type Bar, Baz } from './main.ts'
  1323. </script>`
  1324. )
  1325. expect(content).toMatch(`return { get Baz() { return Baz } }`)
  1326. assertCode(content)
  1327. })
  1328. })
  1329. describe('async/await detection', () => {
  1330. function assertAwaitDetection(code: string, shouldAsync = true) {
  1331. const { content } = compile(`<script setup>${code}</script>`, {
  1332. reactivityTransform: true
  1333. })
  1334. if (shouldAsync) {
  1335. expect(content).toMatch(`let __temp, __restore`)
  1336. }
  1337. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  1338. assertCode(content)
  1339. return content
  1340. }
  1341. test('expression statement', () => {
  1342. assertAwaitDetection(`await foo`)
  1343. })
  1344. test('variable', () => {
  1345. assertAwaitDetection(`const a = 1 + (await foo)`)
  1346. })
  1347. test('ref', () => {
  1348. assertAwaitDetection(`let a = $ref(1 + (await foo))`)
  1349. })
  1350. // #4448
  1351. test('nested await', () => {
  1352. assertAwaitDetection(`await (await foo)`)
  1353. assertAwaitDetection(`await ((await foo))`)
  1354. assertAwaitDetection(`await (await (await foo))`)
  1355. })
  1356. // should prepend semicolon
  1357. test('nested leading await in expression statement', () => {
  1358. const code = assertAwaitDetection(`foo()\nawait 1 + await 2`)
  1359. expect(code).toMatch(`foo()\n;(`)
  1360. })
  1361. // #4596 should NOT prepend semicolon
  1362. test('single line conditions', () => {
  1363. const code = assertAwaitDetection(`if (false) await foo()`)
  1364. expect(code).not.toMatch(`if (false) ;(`)
  1365. })
  1366. test('nested statements', () => {
  1367. assertAwaitDetection(`if (ok) { await foo } else { await bar }`)
  1368. })
  1369. test('multiple `if` nested statements', () => {
  1370. assertAwaitDetection(`if (ok) {
  1371. let a = 'foo'
  1372. await 0 + await 1
  1373. await 2
  1374. } else if (a) {
  1375. await 10
  1376. if (b) {
  1377. await 0 + await 1
  1378. } else {
  1379. let a = 'foo'
  1380. await 2
  1381. }
  1382. if (b) {
  1383. await 3
  1384. await 4
  1385. }
  1386. } else {
  1387. await 5
  1388. }`)
  1389. })
  1390. test('multiple `if while` nested statements', () => {
  1391. assertAwaitDetection(`if (ok) {
  1392. while (d) {
  1393. await 5
  1394. }
  1395. while (d) {
  1396. await 5
  1397. await 6
  1398. if (c) {
  1399. let f = 10
  1400. 10 + await 7
  1401. } else {
  1402. await 8
  1403. await 9
  1404. }
  1405. }
  1406. }`)
  1407. })
  1408. test('multiple `if for` nested statements', () => {
  1409. assertAwaitDetection(`if (ok) {
  1410. for (let a of [1,2,3]) {
  1411. await a
  1412. }
  1413. for (let a of [1,2,3]) {
  1414. await a
  1415. await a
  1416. }
  1417. }`)
  1418. })
  1419. test('should ignore await inside functions', () => {
  1420. // function declaration
  1421. assertAwaitDetection(`async function foo() { await bar }`, false)
  1422. // function expression
  1423. assertAwaitDetection(`const foo = async () => { await bar }`, false)
  1424. // object method
  1425. assertAwaitDetection(`const obj = { async method() { await bar }}`, false)
  1426. // class method
  1427. assertAwaitDetection(
  1428. `const cls = class Foo { async method() { await bar }}`,
  1429. false
  1430. )
  1431. })
  1432. })
  1433. describe('errors', () => {
  1434. test('<script> and <script setup> must have same lang', () => {
  1435. expect(() =>
  1436. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1437. ).toThrow(`<script> and <script setup> must have the same language type`)
  1438. })
  1439. const moduleErrorMsg = `cannot contain ES module exports`
  1440. test('non-type named exports', () => {
  1441. expect(() =>
  1442. compile(`<script setup>
  1443. export const a = 1
  1444. </script>`)
  1445. ).toThrow(moduleErrorMsg)
  1446. expect(() =>
  1447. compile(`<script setup>
  1448. export * from './foo'
  1449. </script>`)
  1450. ).toThrow(moduleErrorMsg)
  1451. expect(() =>
  1452. compile(`<script setup>
  1453. const bar = 1
  1454. export { bar as default }
  1455. </script>`)
  1456. ).toThrow(moduleErrorMsg)
  1457. })
  1458. test('defineProps/Emit() w/ both type and non-type args', () => {
  1459. expect(() => {
  1460. compile(`<script setup lang="ts">
  1461. defineProps<{}>({})
  1462. </script>`)
  1463. }).toThrow(`cannot accept both type and non-type arguments`)
  1464. expect(() => {
  1465. compile(`<script setup lang="ts">
  1466. defineEmits<{}>({})
  1467. </script>`)
  1468. }).toThrow(`cannot accept both type and non-type arguments`)
  1469. })
  1470. test('defineProps/Emit() referencing local var', () => {
  1471. expect(() =>
  1472. compile(`<script setup>
  1473. const bar = 1
  1474. defineProps({
  1475. foo: {
  1476. default: () => bar
  1477. }
  1478. })
  1479. </script>`)
  1480. ).toThrow(`cannot reference locally declared variables`)
  1481. expect(() =>
  1482. compile(`<script setup>
  1483. const bar = 'hello'
  1484. defineEmits([bar])
  1485. </script>`)
  1486. ).toThrow(`cannot reference locally declared variables`)
  1487. // #4644
  1488. expect(() =>
  1489. compile(`
  1490. <script>const bar = 1</script>
  1491. <script setup>
  1492. defineProps({
  1493. foo: {
  1494. default: () => bar
  1495. }
  1496. })
  1497. </script>`)
  1498. ).not.toThrow(`cannot reference locally declared variables`)
  1499. })
  1500. test('should allow defineProps/Emit() referencing scope var', () => {
  1501. assertCode(
  1502. compile(`<script setup>
  1503. const bar = 1
  1504. defineProps({
  1505. foo: {
  1506. default: bar => bar + 1
  1507. }
  1508. })
  1509. defineEmits({
  1510. foo: bar => bar > 1
  1511. })
  1512. </script>`).content
  1513. )
  1514. })
  1515. test('should allow defineProps/Emit() referencing imported binding', () => {
  1516. assertCode(
  1517. compile(`<script setup>
  1518. import { bar } from './bar'
  1519. defineProps({
  1520. foo: {
  1521. default: () => bar
  1522. }
  1523. })
  1524. defineEmits({
  1525. foo: () => bar > 1
  1526. })
  1527. </script>`).content
  1528. )
  1529. })
  1530. })
  1531. })
  1532. describe('SFC analyze <script> bindings', () => {
  1533. it('can parse decorators syntax in typescript block', () => {
  1534. const { scriptAst } = compile(`
  1535. <script lang="ts">
  1536. import { Options, Vue } from 'vue-class-component';
  1537. @Options({
  1538. components: {
  1539. HelloWorld,
  1540. },
  1541. props: ['foo', 'bar']
  1542. })
  1543. export default class Home extends Vue {}
  1544. </script>
  1545. `)
  1546. expect(scriptAst).toBeDefined()
  1547. })
  1548. it('recognizes props array declaration', () => {
  1549. const { bindings } = compile(`
  1550. <script>
  1551. export default {
  1552. props: ['foo', 'bar']
  1553. }
  1554. </script>
  1555. `)
  1556. expect(bindings).toStrictEqual({
  1557. foo: BindingTypes.PROPS,
  1558. bar: BindingTypes.PROPS
  1559. })
  1560. expect(bindings!.__isScriptSetup).toBe(false)
  1561. })
  1562. it('recognizes props object declaration', () => {
  1563. const { bindings } = compile(`
  1564. <script>
  1565. export default {
  1566. props: {
  1567. foo: String,
  1568. bar: {
  1569. type: String,
  1570. },
  1571. baz: null,
  1572. qux: [String, Number]
  1573. }
  1574. }
  1575. </script>
  1576. `)
  1577. expect(bindings).toStrictEqual({
  1578. foo: BindingTypes.PROPS,
  1579. bar: BindingTypes.PROPS,
  1580. baz: BindingTypes.PROPS,
  1581. qux: BindingTypes.PROPS
  1582. })
  1583. expect(bindings!.__isScriptSetup).toBe(false)
  1584. })
  1585. it('recognizes setup return', () => {
  1586. const { bindings } = compile(`
  1587. <script>
  1588. const bar = 2
  1589. export default {
  1590. setup() {
  1591. return {
  1592. foo: 1,
  1593. bar
  1594. }
  1595. }
  1596. }
  1597. </script>
  1598. `)
  1599. expect(bindings).toStrictEqual({
  1600. foo: BindingTypes.SETUP_MAYBE_REF,
  1601. bar: BindingTypes.SETUP_MAYBE_REF
  1602. })
  1603. expect(bindings!.__isScriptSetup).toBe(false)
  1604. })
  1605. it('recognizes exported vars', () => {
  1606. const { bindings } = compile(`
  1607. <script>
  1608. export const foo = 2
  1609. </script>
  1610. <script setup>
  1611. console.log(foo)
  1612. </script>
  1613. `)
  1614. expect(bindings).toStrictEqual({
  1615. foo: BindingTypes.SETUP_CONST
  1616. })
  1617. })
  1618. it('recognizes async setup return', () => {
  1619. const { bindings } = compile(`
  1620. <script>
  1621. const bar = 2
  1622. export default {
  1623. async setup() {
  1624. return {
  1625. foo: 1,
  1626. bar
  1627. }
  1628. }
  1629. }
  1630. </script>
  1631. `)
  1632. expect(bindings).toStrictEqual({
  1633. foo: BindingTypes.SETUP_MAYBE_REF,
  1634. bar: BindingTypes.SETUP_MAYBE_REF
  1635. })
  1636. expect(bindings!.__isScriptSetup).toBe(false)
  1637. })
  1638. it('recognizes data return', () => {
  1639. const { bindings } = compile(`
  1640. <script>
  1641. const bar = 2
  1642. export default {
  1643. data() {
  1644. return {
  1645. foo: null,
  1646. bar
  1647. }
  1648. }
  1649. }
  1650. </script>
  1651. `)
  1652. expect(bindings).toStrictEqual({
  1653. foo: BindingTypes.DATA,
  1654. bar: BindingTypes.DATA
  1655. })
  1656. })
  1657. it('recognizes methods', () => {
  1658. const { bindings } = compile(`
  1659. <script>
  1660. export default {
  1661. methods: {
  1662. foo() {}
  1663. }
  1664. }
  1665. </script>
  1666. `)
  1667. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1668. })
  1669. it('recognizes computeds', () => {
  1670. const { bindings } = compile(`
  1671. <script>
  1672. export default {
  1673. computed: {
  1674. foo() {},
  1675. bar: {
  1676. get() {},
  1677. set() {},
  1678. }
  1679. }
  1680. }
  1681. </script>
  1682. `)
  1683. expect(bindings).toStrictEqual({
  1684. foo: BindingTypes.OPTIONS,
  1685. bar: BindingTypes.OPTIONS
  1686. })
  1687. })
  1688. it('recognizes injections array declaration', () => {
  1689. const { bindings } = compile(`
  1690. <script>
  1691. export default {
  1692. inject: ['foo', 'bar']
  1693. }
  1694. </script>
  1695. `)
  1696. expect(bindings).toStrictEqual({
  1697. foo: BindingTypes.OPTIONS,
  1698. bar: BindingTypes.OPTIONS
  1699. })
  1700. })
  1701. it('recognizes injections object declaration', () => {
  1702. const { bindings } = compile(`
  1703. <script>
  1704. export default {
  1705. inject: {
  1706. foo: {},
  1707. bar: {},
  1708. }
  1709. }
  1710. </script>
  1711. `)
  1712. expect(bindings).toStrictEqual({
  1713. foo: BindingTypes.OPTIONS,
  1714. bar: BindingTypes.OPTIONS
  1715. })
  1716. })
  1717. it('works for mixed bindings', () => {
  1718. const { bindings } = compile(`
  1719. <script>
  1720. export default {
  1721. inject: ['foo'],
  1722. props: {
  1723. bar: String,
  1724. },
  1725. setup() {
  1726. return {
  1727. baz: null,
  1728. }
  1729. },
  1730. data() {
  1731. return {
  1732. qux: null
  1733. }
  1734. },
  1735. methods: {
  1736. quux() {}
  1737. },
  1738. computed: {
  1739. quuz() {}
  1740. }
  1741. }
  1742. </script>
  1743. `)
  1744. expect(bindings).toStrictEqual({
  1745. foo: BindingTypes.OPTIONS,
  1746. bar: BindingTypes.PROPS,
  1747. baz: BindingTypes.SETUP_MAYBE_REF,
  1748. qux: BindingTypes.DATA,
  1749. quux: BindingTypes.OPTIONS,
  1750. quuz: BindingTypes.OPTIONS
  1751. })
  1752. })
  1753. it('works for script setup', () => {
  1754. const { bindings } = compile(`
  1755. <script setup>
  1756. import { ref as r } from 'vue'
  1757. defineProps({
  1758. foo: String
  1759. })
  1760. const a = r(1)
  1761. let b = 2
  1762. const c = 3
  1763. const { d } = someFoo()
  1764. let { e } = someBar()
  1765. </script>
  1766. `)
  1767. expect(bindings).toStrictEqual({
  1768. r: BindingTypes.SETUP_CONST,
  1769. a: BindingTypes.SETUP_REF,
  1770. b: BindingTypes.SETUP_LET,
  1771. c: BindingTypes.SETUP_CONST,
  1772. d: BindingTypes.SETUP_MAYBE_REF,
  1773. e: BindingTypes.SETUP_LET,
  1774. foo: BindingTypes.PROPS
  1775. })
  1776. })
  1777. describe('auto name inference', () => {
  1778. test('basic', () => {
  1779. const { content } = compile(
  1780. `<script setup>const a = 1</script>
  1781. <template>{{ a }}</template>`,
  1782. undefined,
  1783. {
  1784. filename: 'FooBar.vue'
  1785. }
  1786. )
  1787. expect(content).toMatch(`export default {
  1788. __name: 'FooBar'`)
  1789. assertCode(content)
  1790. })
  1791. test('do not overwrite manual name (object)', () => {
  1792. const { content } = compile(
  1793. `<script>
  1794. export default {
  1795. name: 'Baz'
  1796. }
  1797. </script>
  1798. <script setup>const a = 1</script>
  1799. <template>{{ a }}</template>`,
  1800. undefined,
  1801. {
  1802. filename: 'FooBar.vue'
  1803. }
  1804. )
  1805. expect(content).not.toMatch(`name: 'FooBar'`)
  1806. expect(content).toMatch(`name: 'Baz'`)
  1807. assertCode(content)
  1808. })
  1809. test('do not overwrite manual name (call)', () => {
  1810. const { content } = compile(
  1811. `<script>
  1812. import { defineComponent } from 'vue'
  1813. export default defineComponent({
  1814. name: 'Baz'
  1815. })
  1816. </script>
  1817. <script setup>const a = 1</script>
  1818. <template>{{ a }}</template>`,
  1819. undefined,
  1820. {
  1821. filename: 'FooBar.vue'
  1822. }
  1823. )
  1824. expect(content).not.toMatch(`name: 'FooBar'`)
  1825. expect(content).toMatch(`name: 'Baz'`)
  1826. assertCode(content)
  1827. })
  1828. })
  1829. })