compileScript.spec.ts 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  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 compile JS syntax', () => {
  5. const { content } = compile(`
  6. <script setup lang='js'>
  7. const a = 1
  8. const b = 2
  9. </script>
  10. `)
  11. expect(content).toMatch(`return { a, b }`)
  12. assertCode(content)
  13. })
  14. test('should expose top level declarations', () => {
  15. const { content, bindings } = compile(`
  16. <script setup>
  17. import { x } from './x'
  18. let a = 1
  19. const b = 2
  20. function c() {}
  21. class d {}
  22. </script>
  23. <script>
  24. import { xx } from './x'
  25. let aa = 1
  26. const bb = 2
  27. function cc() {}
  28. class dd {}
  29. </script>
  30. `)
  31. expect(content).toMatch(
  32. `return { get aa() { return aa }, set aa(v) { aa = v }, ` +
  33. `bb, cc, dd, get a() { return a }, set a(v) { a = v }, b, c, d, ` +
  34. `get xx() { return xx }, get x() { return x } }`
  35. )
  36. expect(bindings).toStrictEqual({
  37. x: BindingTypes.SETUP_MAYBE_REF,
  38. a: BindingTypes.SETUP_LET,
  39. b: BindingTypes.LITERAL_CONST,
  40. c: BindingTypes.SETUP_CONST,
  41. d: BindingTypes.SETUP_CONST,
  42. xx: BindingTypes.SETUP_MAYBE_REF,
  43. aa: BindingTypes.SETUP_LET,
  44. bb: BindingTypes.LITERAL_CONST,
  45. cc: BindingTypes.SETUP_CONST,
  46. dd: BindingTypes.SETUP_CONST
  47. })
  48. assertCode(content)
  49. })
  50. test('binding analysis for destructure', () => {
  51. const { content, bindings } = compile(`
  52. <script setup>
  53. const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
  54. </script>
  55. `)
  56. expect(content).toMatch('return { foo, bar, baz, y, z }')
  57. expect(bindings).toStrictEqual({
  58. foo: BindingTypes.SETUP_MAYBE_REF,
  59. bar: BindingTypes.SETUP_MAYBE_REF,
  60. baz: BindingTypes.SETUP_MAYBE_REF,
  61. y: BindingTypes.SETUP_MAYBE_REF,
  62. z: BindingTypes.SETUP_MAYBE_REF
  63. })
  64. assertCode(content)
  65. })
  66. test('defineProps()', () => {
  67. const { content, bindings } = compile(`
  68. <script setup>
  69. const props = defineProps({
  70. foo: String
  71. })
  72. const bar = 1
  73. </script>
  74. `)
  75. // should generate working code
  76. assertCode(content)
  77. // should analyze bindings
  78. expect(bindings).toStrictEqual({
  79. foo: BindingTypes.PROPS,
  80. bar: BindingTypes.LITERAL_CONST,
  81. props: BindingTypes.SETUP_REACTIVE_CONST
  82. })
  83. // should remove defineOptions import and call
  84. expect(content).not.toMatch('defineProps')
  85. // should generate correct setup signature
  86. expect(content).toMatch(`setup(__props, { expose: __expose }) {`)
  87. // should assign user identifier to it
  88. expect(content).toMatch(`const props = __props`)
  89. // should include context options in default export
  90. expect(content).toMatch(`export default {
  91. props: {
  92. foo: String
  93. },`)
  94. })
  95. test('defineProps w/ external definition', () => {
  96. const { content } = compile(`
  97. <script setup>
  98. import { propsModel } from './props'
  99. const props = defineProps(propsModel)
  100. </script>
  101. `)
  102. assertCode(content)
  103. expect(content).toMatch(`export default {
  104. props: propsModel,`)
  105. })
  106. // #4764
  107. test('defineProps w/ leading code', () => {
  108. const { content } = compile(`
  109. <script setup>import { x } from './x'
  110. const props = defineProps({})
  111. </script>
  112. `)
  113. // props declaration should be inside setup, not moved along with the import
  114. expect(content).not.toMatch(`const props = __props\nimport`)
  115. assertCode(content)
  116. })
  117. test('defineEmits()', () => {
  118. const { content, bindings } = compile(`
  119. <script setup>
  120. const myEmit = defineEmits(['foo', 'bar'])
  121. </script>
  122. `)
  123. assertCode(content)
  124. expect(bindings).toStrictEqual({
  125. myEmit: BindingTypes.SETUP_CONST
  126. })
  127. // should remove defineEmits import and call
  128. expect(content).not.toMatch('defineEmits')
  129. // should generate correct setup signature
  130. expect(content).toMatch(
  131. `setup(__props, { expose: __expose, emit: myEmit }) {`
  132. )
  133. // should include context options in default export
  134. expect(content).toMatch(`export default {
  135. emits: ['foo', 'bar'],`)
  136. })
  137. test('defineProps/defineEmits in multi-variable declaration', () => {
  138. const { content } = compile(`
  139. <script setup>
  140. const props = defineProps(['item']),
  141. a = 1,
  142. emit = defineEmits(['a']);
  143. </script>
  144. `)
  145. assertCode(content)
  146. expect(content).toMatch(`const a = 1;`) // test correct removal
  147. expect(content).toMatch(`props: ['item'],`)
  148. expect(content).toMatch(`emits: ['a'],`)
  149. })
  150. // #6757
  151. test('defineProps/defineEmits in multi-variable declaration fix #6757 ', () => {
  152. const { content } = compile(`
  153. <script setup>
  154. const a = 1,
  155. props = defineProps(['item']),
  156. emit = defineEmits(['a']);
  157. </script>
  158. `)
  159. assertCode(content)
  160. expect(content).toMatch(`const a = 1;`) // test correct removal
  161. expect(content).toMatch(`props: ['item'],`)
  162. expect(content).toMatch(`emits: ['a'],`)
  163. })
  164. // #7422
  165. test('defineProps/defineEmits in multi-variable declaration fix #7422', () => {
  166. const { content } = compile(`
  167. <script setup>
  168. const props = defineProps(['item']),
  169. emits = defineEmits(['foo']),
  170. a = 0,
  171. b = 0;
  172. </script>
  173. `)
  174. assertCode(content)
  175. expect(content).toMatch(`props: ['item'],`)
  176. expect(content).toMatch(`emits: ['foo'],`)
  177. expect(content).toMatch(`const a = 0,`)
  178. expect(content).toMatch(`b = 0;`)
  179. })
  180. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  181. const { content } = compile(`
  182. <script setup>
  183. const props = defineProps(['item']),
  184. emit = defineEmits(['a']);
  185. </script>
  186. `)
  187. assertCode(content)
  188. expect(content).toMatch(`props: ['item'],`)
  189. expect(content).toMatch(`emits: ['a'],`)
  190. })
  191. describe('defineOptions()', () => {
  192. test('basic usage', () => {
  193. const { content } = compile(`
  194. <script setup>
  195. defineOptions({ name: 'FooApp' })
  196. </script>
  197. `)
  198. assertCode(content)
  199. // should remove defineOptions import and call
  200. expect(content).not.toMatch('defineOptions')
  201. // should include context options in default export
  202. expect(content).toMatch(
  203. `export default /*#__PURE__*/Object.assign({ name: 'FooApp' }, `
  204. )
  205. })
  206. test('empty argument', () => {
  207. const { content } = compile(`
  208. <script setup>
  209. defineOptions()
  210. </script>
  211. `)
  212. assertCode(content)
  213. expect(content).toMatch(`export default {`)
  214. // should remove defineOptions import and call
  215. expect(content).not.toMatch('defineOptions')
  216. })
  217. it('should emit an error with two defineProps', () => {
  218. expect(() =>
  219. compile(`
  220. <script setup>
  221. defineOptions({ name: 'FooApp' })
  222. defineOptions({ name: 'BarApp' })
  223. </script>
  224. `)
  225. ).toThrowError('[@vue/compiler-sfc] duplicate defineOptions() call')
  226. })
  227. it('should emit an error with props or emits property', () => {
  228. expect(() =>
  229. compile(`
  230. <script setup>
  231. defineOptions({ props: { foo: String } })
  232. </script>
  233. `)
  234. ).toThrowError(
  235. '[@vue/compiler-sfc] defineOptions() cannot be used to declare props. Use defineProps() instead.'
  236. )
  237. expect(() =>
  238. compile(`
  239. <script setup>
  240. defineOptions({ emits: ['update'] })
  241. </script>
  242. `)
  243. ).toThrowError(
  244. '[@vue/compiler-sfc] defineOptions() cannot be used to declare emits. Use defineEmits() instead.'
  245. )
  246. expect(() =>
  247. compile(`
  248. <script setup>
  249. defineOptions({ expose: ['foo'] })
  250. </script>
  251. `)
  252. ).toThrowError(
  253. '[@vue/compiler-sfc] defineOptions() cannot be used to declare expose. Use defineExpose() instead.'
  254. )
  255. expect(() =>
  256. compile(`
  257. <script setup>
  258. defineOptions({ slots: ['foo'] })
  259. </script>
  260. `)
  261. ).toThrowError(
  262. '[@vue/compiler-sfc] defineOptions() cannot be used to declare slots. Use defineSlots() instead.'
  263. )
  264. })
  265. it('should emit an error with type generic', () => {
  266. expect(() =>
  267. compile(`
  268. <script setup lang="ts">
  269. defineOptions<{ name: 'FooApp' }>()
  270. </script>
  271. `)
  272. ).toThrowError(
  273. '[@vue/compiler-sfc] defineOptions() cannot accept type arguments'
  274. )
  275. })
  276. it('should emit an error with type assertion', () => {
  277. expect(() =>
  278. compile(`
  279. <script setup lang="ts">
  280. defineOptions({ props: [] } as any)
  281. </script>
  282. `)
  283. ).toThrowError(
  284. '[@vue/compiler-sfc] defineOptions() cannot be used to declare props. Use defineProps() instead.'
  285. )
  286. })
  287. })
  288. test('defineExpose()', () => {
  289. const { content } = compile(`
  290. <script setup>
  291. defineExpose({ foo: 123 })
  292. </script>
  293. `)
  294. assertCode(content)
  295. // should remove defineOptions import and call
  296. expect(content).not.toMatch('defineExpose')
  297. // should generate correct setup signature
  298. expect(content).toMatch(`setup(__props, { expose: __expose }) {`)
  299. // should replace callee
  300. expect(content).toMatch(/\b__expose\(\{ foo: 123 \}\)/)
  301. })
  302. test('<script> after <script setup> the script content not end with `\\n`', () => {
  303. const { content } = compile(`
  304. <script setup>
  305. import { x } from './x'
  306. </script>
  307. <script>const n = 1</script>
  308. `)
  309. assertCode(content)
  310. })
  311. describe('<script> and <script setup> co-usage', () => {
  312. test('script first', () => {
  313. const { content } = compile(`
  314. <script>
  315. export const n = 1
  316. export default {}
  317. </script>
  318. <script setup>
  319. import { x } from './x'
  320. x()
  321. </script>
  322. `)
  323. assertCode(content)
  324. })
  325. test('script setup first', () => {
  326. const { content } = compile(`
  327. <script setup>
  328. import { x } from './x'
  329. x()
  330. </script>
  331. <script>
  332. export const n = 1
  333. export default {}
  334. </script>
  335. `)
  336. assertCode(content)
  337. })
  338. test('script setup first, named default export', () => {
  339. const { content } = compile(`
  340. <script setup>
  341. import { x } from './x'
  342. x()
  343. </script>
  344. <script>
  345. export const n = 1
  346. const def = {}
  347. export { def as default }
  348. </script>
  349. `)
  350. assertCode(content)
  351. })
  352. // #4395
  353. test('script setup first, lang="ts", script block content export default', () => {
  354. const { content } = compile(`
  355. <script setup lang="ts">
  356. import { x } from './x'
  357. x()
  358. </script>
  359. <script lang="ts">
  360. export default {
  361. name: "test"
  362. }
  363. </script>
  364. `)
  365. // ensure __default__ is declared before used
  366. expect(content).toMatch(/const __default__[\S\s]*\.\.\.__default__/m)
  367. assertCode(content)
  368. })
  369. describe('spaces in ExportDefaultDeclaration node', () => {
  370. // #4371
  371. test('with many spaces and newline', () => {
  372. // #4371
  373. const { content } = compile(`
  374. <script>
  375. export const n = 1
  376. export default
  377. {
  378. some:'option'
  379. }
  380. </script>
  381. <script setup>
  382. import { x } from './x'
  383. x()
  384. </script>
  385. `)
  386. assertCode(content)
  387. })
  388. test('with minimal spaces', () => {
  389. const { content } = compile(`
  390. <script>
  391. export const n = 1
  392. export default{
  393. some:'option'
  394. }
  395. </script>
  396. <script setup>
  397. import { x } from './x'
  398. x()
  399. </script>
  400. `)
  401. assertCode(content)
  402. })
  403. })
  404. test('export call expression as default', () => {
  405. const { content } = compile(`
  406. <script>
  407. function fn() {
  408. return "hello, world";
  409. }
  410. export default fn();
  411. </script>
  412. <script setup>
  413. console.log('foo')
  414. </script>
  415. `)
  416. assertCode(content)
  417. })
  418. })
  419. describe('imports', () => {
  420. test('should hoist and expose imports', () => {
  421. assertCode(
  422. compile(`<script setup>
  423. import { ref } from 'vue'
  424. import 'foo/css'
  425. </script>`).content
  426. )
  427. })
  428. test('should extract comment for import or type declarations', () => {
  429. assertCode(
  430. compile(`
  431. <script setup>
  432. import a from 'a' // comment
  433. import b from 'b'
  434. </script>
  435. `).content
  436. )
  437. })
  438. // #2740
  439. test('should allow defineProps/Emit at the start of imports', () => {
  440. assertCode(
  441. compile(`<script setup>
  442. import { ref } from 'vue'
  443. defineProps(['foo'])
  444. defineEmits(['bar'])
  445. const r = ref(0)
  446. </script>`).content
  447. )
  448. })
  449. test('dedupe between user & helper', () => {
  450. const { content } = compile(
  451. `
  452. <script setup>
  453. import { ref } from 'vue'
  454. let foo = $ref(1)
  455. </script>
  456. `,
  457. { reactivityTransform: true }
  458. )
  459. assertCode(content)
  460. expect(content).toMatch(`import { ref } from 'vue'`)
  461. })
  462. test('import dedupe between <script> and <script setup>', () => {
  463. const { content } = compile(`
  464. <script>
  465. import { x } from './x'
  466. </script>
  467. <script setup>
  468. import { x } from './x'
  469. x()
  470. </script>
  471. `)
  472. assertCode(content)
  473. expect(content.indexOf(`import { x }`)).toEqual(
  474. content.lastIndexOf(`import { x }`)
  475. )
  476. })
  477. describe('import ref/reactive function from other place', () => {
  478. test('import directly', () => {
  479. const { bindings } = compile(`
  480. <script setup>
  481. import { ref, reactive } from './foo'
  482. const foo = ref(1)
  483. const bar = reactive(1)
  484. </script>
  485. `)
  486. expect(bindings).toStrictEqual({
  487. ref: BindingTypes.SETUP_MAYBE_REF,
  488. reactive: BindingTypes.SETUP_MAYBE_REF,
  489. foo: BindingTypes.SETUP_MAYBE_REF,
  490. bar: BindingTypes.SETUP_MAYBE_REF
  491. })
  492. })
  493. test('import w/ alias', () => {
  494. const { bindings } = compile(`
  495. <script setup>
  496. import { ref as _ref, reactive as _reactive } from './foo'
  497. const foo = ref(1)
  498. const bar = reactive(1)
  499. </script>
  500. `)
  501. expect(bindings).toStrictEqual({
  502. _reactive: BindingTypes.SETUP_MAYBE_REF,
  503. _ref: BindingTypes.SETUP_MAYBE_REF,
  504. foo: BindingTypes.SETUP_MAYBE_REF,
  505. bar: BindingTypes.SETUP_MAYBE_REF
  506. })
  507. })
  508. test('aliased usage before import site', () => {
  509. const { bindings } = compile(`
  510. <script setup>
  511. const bar = x(1)
  512. import { reactive as x } from 'vue'
  513. </script>
  514. `)
  515. expect(bindings).toStrictEqual({
  516. bar: BindingTypes.SETUP_REACTIVE_CONST,
  517. x: BindingTypes.SETUP_CONST
  518. })
  519. })
  520. })
  521. test('should support module string names syntax', () => {
  522. const { content, bindings } = compile(`
  523. <script>
  524. import { "😏" as foo } from './foo'
  525. </script>
  526. <script setup>
  527. import { "😏" as foo } from './foo'
  528. </script>
  529. `)
  530. assertCode(content)
  531. expect(bindings).toStrictEqual({
  532. foo: BindingTypes.SETUP_MAYBE_REF
  533. })
  534. })
  535. })
  536. // in dev mode, declared bindings are returned as an object from setup()
  537. // when using TS, users may import types which should not be returned as
  538. // values, so we need to check import usage in the template to determine
  539. // what to be returned.
  540. describe('dev mode import usage check', () => {
  541. test('components', () => {
  542. const { content } = compile(`
  543. <script setup lang="ts">
  544. import { FooBar, FooBaz, FooQux, foo } from './x'
  545. const fooBar: FooBar = 1
  546. </script>
  547. <template>
  548. <FooBaz></FooBaz>
  549. <foo-qux/>
  550. <foo/>
  551. FooBar
  552. </template>
  553. `)
  554. // FooBar: should not be matched by plain text or incorrect case
  555. // FooBaz: used as PascalCase component
  556. // FooQux: used as kebab-case component
  557. // foo: lowercase component
  558. expect(content).toMatch(
  559. `return { fooBar, get FooBaz() { return FooBaz }, ` +
  560. `get FooQux() { return FooQux }, get foo() { return foo } }`
  561. )
  562. assertCode(content)
  563. })
  564. test('directive', () => {
  565. const { content } = compile(`
  566. <script setup lang="ts">
  567. import { vMyDir } from './x'
  568. </script>
  569. <template>
  570. <div v-my-dir></div>
  571. </template>
  572. `)
  573. expect(content).toMatch(`return { get vMyDir() { return vMyDir } }`)
  574. assertCode(content)
  575. })
  576. // https://github.com/vuejs/core/issues/4599
  577. test('attribute expressions', () => {
  578. const { content } = compile(`
  579. <script setup lang="ts">
  580. import { bar, baz } from './x'
  581. const cond = true
  582. </script>
  583. <template>
  584. <div :class="[cond ? '' : bar(), 'default']" :style="baz"></div>
  585. </template>
  586. `)
  587. expect(content).toMatch(
  588. `return { cond, get bar() { return bar }, get baz() { return baz } }`
  589. )
  590. assertCode(content)
  591. })
  592. test('vue interpolations', () => {
  593. const { content } = compile(`
  594. <script setup lang="ts">
  595. import { x, y, z, x$y } from './x'
  596. </script>
  597. <template>
  598. <div :id="z + 'y'">{{ x }} {{ yy }} {{ x$y }}</div>
  599. </template>
  600. `)
  601. // x: used in interpolation
  602. // y: should not be matched by {{ yy }} or 'y' in binding exps
  603. // x$y: #4274 should escape special chars when creating Regex
  604. expect(content).toMatch(
  605. `return { get x() { return x }, get z() { return z }, get x$y() { return x$y } }`
  606. )
  607. assertCode(content)
  608. })
  609. // #4340 interpolations in template strings
  610. test('js template string interpolations', () => {
  611. const { content } = compile(`
  612. <script setup lang="ts">
  613. import { VAR, VAR2, VAR3 } from './x'
  614. </script>
  615. <template>
  616. {{ \`\${VAR}VAR2\${VAR3}\` }}
  617. </template>
  618. `)
  619. // VAR2 should not be matched
  620. expect(content).toMatch(
  621. `return { get VAR() { return VAR }, get VAR3() { return VAR3 } }`
  622. )
  623. assertCode(content)
  624. })
  625. // edge case: last tag in template
  626. test('last tag', () => {
  627. const { content } = compile(`
  628. <script setup lang="ts">
  629. import { FooBaz, Last } from './x'
  630. </script>
  631. <template>
  632. <FooBaz></FooBaz>
  633. <Last/>
  634. </template>
  635. `)
  636. expect(content).toMatch(
  637. `return { get FooBaz() { return FooBaz }, get Last() { return Last } }`
  638. )
  639. assertCode(content)
  640. })
  641. test('TS annotations', () => {
  642. const { content } = compile(`
  643. <script setup lang="ts">
  644. import { Foo, Bar, Baz, Qux, Fred } from './x'
  645. const a = 1
  646. function b() {}
  647. </script>
  648. <template>
  649. {{ a as Foo }}
  650. {{ b<Bar>() }}
  651. {{ Baz }}
  652. <Comp v-slot="{ data }: Qux">{{ data }}</Comp>
  653. <div v-for="{ z = x as Qux } in list as Fred"/>
  654. </template>
  655. `)
  656. expect(content).toMatch(`return { a, b, get Baz() { return Baz } }`)
  657. assertCode(content)
  658. })
  659. // vuejs/vue#12591
  660. test('v-on inline statement', () => {
  661. // should not error
  662. compile(`
  663. <script setup lang="ts">
  664. import { foo } from './foo'
  665. </script>
  666. <template>
  667. <div @click="$emit('update:a');"></div>
  668. </template>
  669. `)
  670. })
  671. })
  672. describe('inlineTemplate mode', () => {
  673. test('should work', () => {
  674. const { content } = compile(
  675. `
  676. <script setup>
  677. import { ref } from 'vue'
  678. const count = ref(0)
  679. </script>
  680. <template>
  681. <div>{{ count }}</div>
  682. <div>static</div>
  683. </template>
  684. `,
  685. { inlineTemplate: true }
  686. )
  687. // check snapshot and make sure helper imports and
  688. // hoists are placed correctly.
  689. assertCode(content)
  690. // in inline mode, no need to call expose() since nothing is exposed
  691. // anyway!
  692. expect(content).not.toMatch(`expose()`)
  693. })
  694. test('with defineExpose()', () => {
  695. const { content } = compile(
  696. `
  697. <script setup>
  698. const count = ref(0)
  699. defineExpose({ count })
  700. </script>
  701. `,
  702. { inlineTemplate: true }
  703. )
  704. assertCode(content)
  705. expect(content).toMatch(`setup(__props, { expose: __expose })`)
  706. expect(content).toMatch(`expose({ count })`)
  707. })
  708. test('referencing scope components and directives', () => {
  709. const { content } = compile(
  710. `
  711. <script setup>
  712. import ChildComp from './Child.vue'
  713. import SomeOtherComp from './Other.vue'
  714. import vMyDir from './my-dir'
  715. </script>
  716. <template>
  717. <div v-my-dir></div>
  718. <ChildComp/>
  719. <some-other-comp/>
  720. </template>
  721. `,
  722. { inlineTemplate: true }
  723. )
  724. expect(content).toMatch('[_unref(vMyDir)]')
  725. expect(content).toMatch('_createVNode(ChildComp)')
  726. // kebab-case component support
  727. expect(content).toMatch('_createVNode(SomeOtherComp)')
  728. assertCode(content)
  729. })
  730. test('avoid unref() when necessary', () => {
  731. // function, const, component import
  732. const { content } = compile(
  733. `<script setup>
  734. import { ref } from 'vue'
  735. import Foo, { bar } from './Foo.vue'
  736. import other from './util'
  737. import * as tree from './tree'
  738. const count = ref(0)
  739. const constant = {}
  740. const maybe = foo()
  741. let lett = 1
  742. function fn() {}
  743. </script>
  744. <template>
  745. <Foo>{{ bar }}</Foo>
  746. <div @click="fn">{{ count }} {{ constant }} {{ maybe }} {{ lett }} {{ other }}</div>
  747. {{ tree.foo() }}
  748. </template>
  749. `,
  750. { inlineTemplate: true }
  751. )
  752. // no need to unref vue component import
  753. expect(content).toMatch(`createVNode(Foo,`)
  754. // #2699 should unref named imports from .vue
  755. expect(content).toMatch(`unref(bar)`)
  756. // should unref other imports
  757. expect(content).toMatch(`unref(other)`)
  758. // no need to unref constant literals
  759. expect(content).not.toMatch(`unref(constant)`)
  760. // should directly use .value for known refs
  761. expect(content).toMatch(`count.value`)
  762. // should unref() on const bindings that may be refs
  763. expect(content).toMatch(`unref(maybe)`)
  764. // should unref() on let bindings
  765. expect(content).toMatch(`unref(lett)`)
  766. // no need to unref namespace import (this also preserves tree-shaking)
  767. expect(content).toMatch(`tree.foo()`)
  768. // no need to unref function declarations
  769. expect(content).toMatch(`{ onClick: fn }`)
  770. // no need to mark constant fns in patch flag
  771. expect(content).not.toMatch(`PROPS`)
  772. assertCode(content)
  773. })
  774. test('v-model codegen', () => {
  775. const { content } = compile(
  776. `<script setup>
  777. import { ref } from 'vue'
  778. const count = ref(0)
  779. const maybe = foo()
  780. let lett = 1
  781. </script>
  782. <template>
  783. <input v-model="count">
  784. <input v-model="maybe">
  785. <input v-model="lett">
  786. </template>
  787. `,
  788. { inlineTemplate: true }
  789. )
  790. // known const ref: set value
  791. expect(content).toMatch(`(count).value = $event`)
  792. // const but maybe ref: assign if ref, otherwise do nothing
  793. expect(content).toMatch(`_isRef(maybe) ? (maybe).value = $event : null`)
  794. // let: handle both cases
  795. expect(content).toMatch(
  796. `_isRef(lett) ? (lett).value = $event : lett = $event`
  797. )
  798. assertCode(content)
  799. })
  800. test('v-model should not generate ref assignment code for non-setup bindings', () => {
  801. const { content } = compile(
  802. `<script setup>
  803. import { ref } from 'vue'
  804. const count = ref(0)
  805. </script>
  806. <script>
  807. export default {
  808. data() { return { foo: 123 } }
  809. }
  810. </script>
  811. <template>
  812. <input v-model="foo">
  813. </template>
  814. `,
  815. { inlineTemplate: true }
  816. )
  817. expect(content).not.toMatch(`_isRef(foo)`)
  818. })
  819. test('template assignment expression codegen', () => {
  820. const { content } = compile(
  821. `<script setup>
  822. import { ref } from 'vue'
  823. const count = ref(0)
  824. const maybe = foo()
  825. let lett = 1
  826. let v = ref(1)
  827. </script>
  828. <template>
  829. <div @click="count = 1"/>
  830. <div @click="maybe = count"/>
  831. <div @click="lett = count"/>
  832. <div @click="v += 1"/>
  833. <div @click="v -= 1"/>
  834. <div @click="() => {
  835. let a = '' + lett
  836. v = a
  837. }"/>
  838. <div @click="() => {
  839. // nested scopes
  840. (()=>{
  841. let x = a
  842. (()=>{
  843. let z = x
  844. let z2 = z
  845. })
  846. let lz = z
  847. })
  848. v = a
  849. }"/>
  850. </template>
  851. `,
  852. { inlineTemplate: true }
  853. )
  854. // known const ref: set value
  855. expect(content).toMatch(`count.value = 1`)
  856. // const but maybe ref: only assign after check
  857. expect(content).toMatch(`maybe.value = count.value`)
  858. // let: handle both cases
  859. expect(content).toMatch(
  860. `_isRef(lett) ? lett.value = count.value : lett = count.value`
  861. )
  862. expect(content).toMatch(`_isRef(v) ? v.value += 1 : v += 1`)
  863. expect(content).toMatch(`_isRef(v) ? v.value -= 1 : v -= 1`)
  864. expect(content).toMatch(`_isRef(v) ? v.value = a : v = a`)
  865. expect(content).toMatch(`_isRef(v) ? v.value = _ctx.a : v = _ctx.a`)
  866. assertCode(content)
  867. })
  868. test('template update expression codegen', () => {
  869. const { content } = compile(
  870. `<script setup>
  871. import { ref } from 'vue'
  872. const count = ref(0)
  873. const maybe = foo()
  874. let lett = 1
  875. </script>
  876. <template>
  877. <div @click="count++"/>
  878. <div @click="--count"/>
  879. <div @click="maybe++"/>
  880. <div @click="--maybe"/>
  881. <div @click="lett++"/>
  882. <div @click="--lett"/>
  883. </template>
  884. `,
  885. { inlineTemplate: true }
  886. )
  887. // known const ref: set value
  888. expect(content).toMatch(`count.value++`)
  889. expect(content).toMatch(`--count.value`)
  890. // const but maybe ref (non-ref case ignored)
  891. expect(content).toMatch(`maybe.value++`)
  892. expect(content).toMatch(`--maybe.value`)
  893. // let: handle both cases
  894. expect(content).toMatch(`_isRef(lett) ? lett.value++ : lett++`)
  895. expect(content).toMatch(`_isRef(lett) ? --lett.value : --lett`)
  896. assertCode(content)
  897. })
  898. test('template destructure assignment codegen', () => {
  899. const { content } = compile(
  900. `<script setup>
  901. import { ref } from 'vue'
  902. const val = {}
  903. const count = ref(0)
  904. const maybe = foo()
  905. let lett = 1
  906. </script>
  907. <template>
  908. <div @click="({ count } = val)"/>
  909. <div @click="[maybe] = val"/>
  910. <div @click="({ lett } = val)"/>
  911. </template>
  912. `,
  913. { inlineTemplate: true }
  914. )
  915. // known const ref: set value
  916. expect(content).toMatch(`({ count: count.value } = val)`)
  917. // const but maybe ref (non-ref case ignored)
  918. expect(content).toMatch(`[maybe.value] = val`)
  919. // let: assumes non-ref
  920. expect(content).toMatch(`{ lett: lett } = val`)
  921. assertCode(content)
  922. })
  923. test('ssr codegen', () => {
  924. const { content } = compile(
  925. `
  926. <script setup>
  927. import { ref } from 'vue'
  928. const count = ref(0)
  929. </script>
  930. <template>
  931. <div>{{ count }}</div>
  932. <div>static</div>
  933. </template>
  934. <style>
  935. div { color: v-bind(count) }
  936. </style>
  937. `,
  938. {
  939. inlineTemplate: true,
  940. templateOptions: {
  941. ssr: true
  942. }
  943. }
  944. )
  945. expect(content).toMatch(`\n __ssrInlineRender: true,\n`)
  946. expect(content).toMatch(`return (_ctx, _push`)
  947. expect(content).toMatch(`ssrInterpolate`)
  948. expect(content).not.toMatch(`useCssVars`)
  949. expect(content).toMatch(`"--${mockId}-count": (count.value)`)
  950. assertCode(content)
  951. })
  952. })
  953. describe('with TypeScript', () => {
  954. test('hoist type declarations', () => {
  955. const { content } = compile(`
  956. <script setup lang="ts">
  957. export interface Foo {}
  958. type Bar = {}
  959. </script>`)
  960. assertCode(content)
  961. })
  962. test('defineProps/Emit w/ runtime options', () => {
  963. const { content } = compile(`
  964. <script setup lang="ts">
  965. const props = defineProps({ foo: String })
  966. const emit = defineEmits(['a', 'b'])
  967. </script>
  968. `)
  969. assertCode(content)
  970. expect(content).toMatch(`export default /*#__PURE__*/_defineComponent({
  971. props: { foo: String },
  972. emits: ['a', 'b'],
  973. setup(__props, { expose: __expose, emit }) {`)
  974. })
  975. test('defineProps w/ type', () => {
  976. const { content, bindings } = compile(`
  977. <script setup lang="ts">
  978. interface Test {}
  979. type Alias = number[]
  980. defineProps<{
  981. string: string
  982. number: number
  983. boolean: boolean
  984. object: object
  985. objectLiteral: { a: number }
  986. fn: (n: number) => void
  987. functionRef: Function
  988. objectRef: Object
  989. dateTime: Date
  990. array: string[]
  991. arrayRef: Array<any>
  992. tuple: [number, number]
  993. set: Set<string>
  994. literal: 'foo'
  995. optional?: any
  996. recordRef: Record<string, null>
  997. interface: Test
  998. alias: Alias
  999. method(): void
  1000. symbol: symbol
  1001. extract: Extract<1 | 2 | boolean, 2>
  1002. exclude: Exclude<1 | 2 | boolean, 2>
  1003. uppercase: Uppercase<'foo'>
  1004. params: Parameters<(foo: any) => void>
  1005. nonNull: NonNullable<string | null>
  1006. objectOrFn: {
  1007. (): void
  1008. foo: string
  1009. }
  1010. union: string | number
  1011. literalUnion: 'foo' | 'bar'
  1012. literalUnionNumber: 1 | 2 | 3 | 4 | 5
  1013. literalUnionMixed: 'foo' | 1 | boolean
  1014. intersection: Test & {}
  1015. intersection2: 'foo' & ('foo' | 'bar')
  1016. foo: ((item: any) => boolean) | null
  1017. unknown: UnknownType
  1018. unknownUnion: UnknownType | string
  1019. unknownIntersection: UnknownType & Object
  1020. unknownUnionWithBoolean: UnknownType | boolean
  1021. unknownUnionWithFunction: UnknownType | (() => any)
  1022. }>()
  1023. </script>`)
  1024. assertCode(content)
  1025. expect(content).toMatch(`string: { type: String, required: true }`)
  1026. expect(content).toMatch(`number: { type: Number, required: true }`)
  1027. expect(content).toMatch(`boolean: { type: Boolean, required: true }`)
  1028. expect(content).toMatch(`object: { type: Object, required: true }`)
  1029. expect(content).toMatch(`objectLiteral: { type: Object, required: true }`)
  1030. expect(content).toMatch(`fn: { type: Function, required: true }`)
  1031. expect(content).toMatch(`functionRef: { type: Function, required: true }`)
  1032. expect(content).toMatch(`objectRef: { type: Object, required: true }`)
  1033. expect(content).toMatch(`dateTime: { type: Date, required: true }`)
  1034. expect(content).toMatch(`array: { type: Array, required: true }`)
  1035. expect(content).toMatch(`arrayRef: { type: Array, required: true }`)
  1036. expect(content).toMatch(`tuple: { type: Array, required: true }`)
  1037. expect(content).toMatch(`set: { type: Set, required: true }`)
  1038. expect(content).toMatch(`literal: { type: String, required: true }`)
  1039. expect(content).toMatch(`optional: { type: null, required: false }`)
  1040. expect(content).toMatch(`recordRef: { type: Object, required: true }`)
  1041. expect(content).toMatch(`interface: { type: Object, required: true }`)
  1042. expect(content).toMatch(`alias: { type: Array, required: true }`)
  1043. expect(content).toMatch(`method: { type: Function, required: true }`)
  1044. expect(content).toMatch(`symbol: { type: Symbol, required: true }`)
  1045. expect(content).toMatch(
  1046. `objectOrFn: { type: [Function, Object], required: true },`
  1047. )
  1048. expect(content).toMatch(`extract: { type: Number, required: true }`)
  1049. expect(content).toMatch(
  1050. `exclude: { type: [Number, Boolean], required: true }`
  1051. )
  1052. expect(content).toMatch(`uppercase: { type: String, required: true }`)
  1053. expect(content).toMatch(`params: { type: Array, required: true }`)
  1054. expect(content).toMatch(`nonNull: { type: String, required: true }`)
  1055. expect(content).toMatch(
  1056. `union: { type: [String, Number], required: true }`
  1057. )
  1058. expect(content).toMatch(`literalUnion: { type: String, required: true }`)
  1059. expect(content).toMatch(
  1060. `literalUnionNumber: { type: Number, required: true }`
  1061. )
  1062. expect(content).toMatch(
  1063. `literalUnionMixed: { type: [String, Number, Boolean], required: true }`
  1064. )
  1065. expect(content).toMatch(`intersection: { type: Object, required: true }`)
  1066. expect(content).toMatch(`intersection2: { type: String, required: true }`)
  1067. expect(content).toMatch(`foo: { type: [Function, null], required: true }`)
  1068. expect(content).toMatch(`unknown: { type: null, required: true }`)
  1069. // uninon containing unknown type: skip check
  1070. expect(content).toMatch(`unknownUnion: { type: null, required: true }`)
  1071. // intersection containing unknown type: narrow to the known types
  1072. expect(content).toMatch(
  1073. `unknownIntersection: { type: Object, required: true },`
  1074. )
  1075. expect(content).toMatch(
  1076. `unknownUnionWithBoolean: { type: Boolean, required: true, skipCheck: true },`
  1077. )
  1078. expect(content).toMatch(
  1079. `unknownUnionWithFunction: { type: Function, required: true, skipCheck: true }`
  1080. )
  1081. expect(bindings).toStrictEqual({
  1082. string: BindingTypes.PROPS,
  1083. number: BindingTypes.PROPS,
  1084. boolean: BindingTypes.PROPS,
  1085. object: BindingTypes.PROPS,
  1086. objectLiteral: BindingTypes.PROPS,
  1087. fn: BindingTypes.PROPS,
  1088. functionRef: BindingTypes.PROPS,
  1089. objectRef: BindingTypes.PROPS,
  1090. dateTime: BindingTypes.PROPS,
  1091. array: BindingTypes.PROPS,
  1092. arrayRef: BindingTypes.PROPS,
  1093. tuple: BindingTypes.PROPS,
  1094. set: BindingTypes.PROPS,
  1095. literal: BindingTypes.PROPS,
  1096. optional: BindingTypes.PROPS,
  1097. recordRef: BindingTypes.PROPS,
  1098. interface: BindingTypes.PROPS,
  1099. alias: BindingTypes.PROPS,
  1100. method: BindingTypes.PROPS,
  1101. symbol: BindingTypes.PROPS,
  1102. objectOrFn: BindingTypes.PROPS,
  1103. extract: BindingTypes.PROPS,
  1104. exclude: BindingTypes.PROPS,
  1105. union: BindingTypes.PROPS,
  1106. literalUnion: BindingTypes.PROPS,
  1107. literalUnionNumber: BindingTypes.PROPS,
  1108. literalUnionMixed: BindingTypes.PROPS,
  1109. intersection: BindingTypes.PROPS,
  1110. intersection2: BindingTypes.PROPS,
  1111. foo: BindingTypes.PROPS,
  1112. uppercase: BindingTypes.PROPS,
  1113. params: BindingTypes.PROPS,
  1114. nonNull: BindingTypes.PROPS,
  1115. unknown: BindingTypes.PROPS,
  1116. unknownUnion: BindingTypes.PROPS,
  1117. unknownIntersection: BindingTypes.PROPS,
  1118. unknownUnionWithBoolean: BindingTypes.PROPS,
  1119. unknownUnionWithFunction: BindingTypes.PROPS
  1120. })
  1121. })
  1122. test('defineProps w/ interface', () => {
  1123. const { content, bindings } = compile(`
  1124. <script setup lang="ts">
  1125. interface Props { x?: number }
  1126. defineProps<Props>()
  1127. </script>
  1128. `)
  1129. assertCode(content)
  1130. expect(content).toMatch(`x: { type: Number, required: false }`)
  1131. expect(bindings).toStrictEqual({
  1132. x: BindingTypes.PROPS
  1133. })
  1134. })
  1135. test('defineProps w/ extends interface', () => {
  1136. const { content, bindings } = compile(`
  1137. <script lang="ts">
  1138. interface Foo { x?: number }
  1139. </script>
  1140. <script setup lang="ts">
  1141. interface Bar extends Foo { y?: number }
  1142. interface Props extends Bar {
  1143. z: number
  1144. y: string
  1145. }
  1146. defineProps<Props>()
  1147. </script>
  1148. `)
  1149. assertCode(content)
  1150. expect(content).toMatch(`z: { type: Number, required: true }`)
  1151. expect(content).toMatch(`y: { type: String, required: true }`)
  1152. expect(content).toMatch(`x: { type: Number, required: false }`)
  1153. expect(bindings).toStrictEqual({
  1154. x: BindingTypes.PROPS,
  1155. y: BindingTypes.PROPS,
  1156. z: BindingTypes.PROPS
  1157. })
  1158. })
  1159. test('defineProps w/ exported interface', () => {
  1160. const { content, bindings } = compile(`
  1161. <script setup lang="ts">
  1162. export interface Props { x?: number }
  1163. defineProps<Props>()
  1164. </script>
  1165. `)
  1166. assertCode(content)
  1167. expect(content).toMatch(`x: { type: Number, required: false }`)
  1168. expect(bindings).toStrictEqual({
  1169. x: BindingTypes.PROPS
  1170. })
  1171. })
  1172. test('defineProps w/ exported interface in normal script', () => {
  1173. const { content, bindings } = compile(`
  1174. <script lang="ts">
  1175. export interface Props { x?: number }
  1176. </script>
  1177. <script setup lang="ts">
  1178. defineProps<Props>()
  1179. </script>
  1180. `)
  1181. assertCode(content)
  1182. expect(content).toMatch(`x: { type: Number, required: false }`)
  1183. expect(bindings).toStrictEqual({
  1184. x: BindingTypes.PROPS
  1185. })
  1186. })
  1187. test('defineProps w/ type alias', () => {
  1188. const { content, bindings } = compile(`
  1189. <script setup lang="ts">
  1190. type Props = { x?: number }
  1191. defineProps<Props>()
  1192. </script>
  1193. `)
  1194. assertCode(content)
  1195. expect(content).toMatch(`x: { type: Number, required: false }`)
  1196. expect(bindings).toStrictEqual({
  1197. x: BindingTypes.PROPS
  1198. })
  1199. })
  1200. test('defineProps w/ exported type alias', () => {
  1201. const { content, bindings } = compile(`
  1202. <script setup lang="ts">
  1203. export type Props = { x?: number }
  1204. defineProps<Props>()
  1205. </script>
  1206. `)
  1207. assertCode(content)
  1208. expect(content).toMatch(`x: { type: Number, required: false }`)
  1209. expect(bindings).toStrictEqual({
  1210. x: BindingTypes.PROPS
  1211. })
  1212. })
  1213. test('defineProps w/ TS assertion', () => {
  1214. const { content, bindings } = compile(`
  1215. <script setup lang="ts">
  1216. defineProps(['foo'])! as any
  1217. </script>
  1218. `)
  1219. expect(content).toMatch(`props: ['foo']`)
  1220. assertCode(content)
  1221. expect(bindings).toStrictEqual({
  1222. foo: BindingTypes.PROPS
  1223. })
  1224. })
  1225. test('withDefaults (static)', () => {
  1226. const { content, bindings } = compile(`
  1227. <script setup lang="ts">
  1228. const props = withDefaults(defineProps<{
  1229. foo?: string
  1230. bar?: number;
  1231. baz: boolean;
  1232. qux?(): number;
  1233. quux?(): void
  1234. quuxx?: Promise<string>;
  1235. fred?: string
  1236. }>(), {
  1237. foo: 'hi',
  1238. qux() { return 1 },
  1239. ['quux']() { },
  1240. async quuxx() { return await Promise.resolve('hi') },
  1241. get fred() { return 'fred' }
  1242. })
  1243. </script>
  1244. `)
  1245. assertCode(content)
  1246. expect(content).toMatch(
  1247. `foo: { type: String, required: false, default: 'hi' }`
  1248. )
  1249. expect(content).toMatch(`bar: { type: Number, required: false }`)
  1250. expect(content).toMatch(`baz: { type: Boolean, required: true }`)
  1251. expect(content).toMatch(
  1252. `qux: { type: Function, required: false, default() { return 1 } }`
  1253. )
  1254. expect(content).toMatch(
  1255. `quux: { type: Function, required: false, default() { } }`
  1256. )
  1257. expect(content).toMatch(
  1258. `quuxx: { type: Promise, required: false, async default() { return await Promise.resolve('hi') } }`
  1259. )
  1260. expect(content).toMatch(
  1261. `fred: { type: String, required: false, get default() { return 'fred' } }`
  1262. )
  1263. expect(content).toMatch(
  1264. `{ foo: string, bar?: number, baz: boolean, qux(): number, quux(): void, quuxx: Promise<string>, fred: string }`
  1265. )
  1266. expect(content).toMatch(`const props = __props`)
  1267. expect(bindings).toStrictEqual({
  1268. foo: BindingTypes.PROPS,
  1269. bar: BindingTypes.PROPS,
  1270. baz: BindingTypes.PROPS,
  1271. qux: BindingTypes.PROPS,
  1272. quux: BindingTypes.PROPS,
  1273. quuxx: BindingTypes.PROPS,
  1274. fred: BindingTypes.PROPS,
  1275. props: BindingTypes.SETUP_CONST
  1276. })
  1277. })
  1278. test('withDefaults (static) + normal script', () => {
  1279. const { content } = compile(`
  1280. <script lang="ts">
  1281. interface Props {
  1282. a?: string;
  1283. }
  1284. </script>
  1285. <script setup lang="ts">
  1286. const props = withDefaults(defineProps<Props>(), {
  1287. a: "a",
  1288. });
  1289. </script>
  1290. `)
  1291. assertCode(content)
  1292. })
  1293. // #7111
  1294. test('withDefaults (static) w/ production mode', () => {
  1295. const { content } = compile(
  1296. `
  1297. <script setup lang="ts">
  1298. const props = withDefaults(defineProps<{
  1299. foo: () => void
  1300. bar: boolean
  1301. baz: boolean | (() => void)
  1302. qux: string | number
  1303. }>(), {
  1304. baz: true,
  1305. qux: 'hi'
  1306. })
  1307. </script>
  1308. `,
  1309. { isProd: true }
  1310. )
  1311. assertCode(content)
  1312. expect(content).toMatch(`const props = __props`)
  1313. // foo has no default value, the Function can be dropped
  1314. expect(content).toMatch(`foo: null`)
  1315. expect(content).toMatch(`bar: { type: Boolean }`)
  1316. expect(content).toMatch(
  1317. `baz: { type: [Boolean, Function], default: true }`
  1318. )
  1319. expect(content).toMatch(`qux: { default: 'hi' }`)
  1320. })
  1321. test('withDefaults (dynamic)', () => {
  1322. const { content } = compile(`
  1323. <script setup lang="ts">
  1324. import { defaults } from './foo'
  1325. const props = withDefaults(defineProps<{
  1326. foo?: string
  1327. bar?: number
  1328. baz: boolean
  1329. }>(), { ...defaults })
  1330. </script>
  1331. `)
  1332. assertCode(content)
  1333. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1334. expect(content).toMatch(
  1335. `
  1336. _mergeDefaults({
  1337. foo: { type: String, required: false },
  1338. bar: { type: Number, required: false },
  1339. baz: { type: Boolean, required: true }
  1340. }, { ...defaults })`.trim()
  1341. )
  1342. })
  1343. test('withDefaults (reference)', () => {
  1344. const { content } = compile(`
  1345. <script setup lang="ts">
  1346. import { defaults } from './foo'
  1347. const props = withDefaults(defineProps<{
  1348. foo?: string
  1349. bar?: number
  1350. baz: boolean
  1351. }>(), defaults)
  1352. </script>
  1353. `)
  1354. assertCode(content)
  1355. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1356. expect(content).toMatch(
  1357. `
  1358. _mergeDefaults({
  1359. foo: { type: String, required: false },
  1360. bar: { type: Number, required: false },
  1361. baz: { type: Boolean, required: true }
  1362. }, defaults)`.trim()
  1363. )
  1364. })
  1365. // #7111
  1366. test('withDefaults (dynamic) w/ production mode', () => {
  1367. const { content } = compile(
  1368. `
  1369. <script setup lang="ts">
  1370. import { defaults } from './foo'
  1371. const props = withDefaults(defineProps<{
  1372. foo: () => void
  1373. bar: boolean
  1374. baz: boolean | (() => void)
  1375. qux: string | number
  1376. }>(), { ...defaults })
  1377. </script>
  1378. `,
  1379. { isProd: true }
  1380. )
  1381. assertCode(content)
  1382. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1383. expect(content).toMatch(
  1384. `
  1385. _mergeDefaults({
  1386. foo: { type: Function },
  1387. bar: { type: Boolean },
  1388. baz: { type: [Boolean, Function] },
  1389. qux: null
  1390. }, { ...defaults })`.trim()
  1391. )
  1392. })
  1393. test('withDefaults w/ dynamic object method', () => {
  1394. const { content } = compile(`
  1395. <script setup lang="ts">
  1396. const props = withDefaults(defineProps<{
  1397. foo?: () => 'string'
  1398. }>(), {
  1399. ['fo' + 'o']() { return 'foo' }
  1400. })
  1401. </script>
  1402. `)
  1403. assertCode(content)
  1404. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  1405. expect(content).toMatch(
  1406. `
  1407. _mergeDefaults({
  1408. foo: { type: Function, required: false }
  1409. }, {
  1410. ['fo' + 'o']() { return 'foo' }
  1411. })`.trim()
  1412. )
  1413. })
  1414. test('defineEmits w/ type', () => {
  1415. const { content } = compile(`
  1416. <script setup lang="ts">
  1417. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  1418. </script>
  1419. `)
  1420. assertCode(content)
  1421. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1422. })
  1423. test('defineEmits w/ type (union)', () => {
  1424. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  1425. expect(() =>
  1426. compile(`
  1427. <script setup lang="ts">
  1428. const emit = defineEmits<${type}>()
  1429. </script>
  1430. `)
  1431. ).toThrow()
  1432. })
  1433. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  1434. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  1435. const { content } = compile(`
  1436. <script setup lang="ts">
  1437. const emit = defineEmits<${type}>()
  1438. </script>
  1439. `)
  1440. assertCode(content)
  1441. expect(content).toMatch(`emits: ["foo", "bar", "baz"]`)
  1442. })
  1443. test('defineEmits w/ type (interface)', () => {
  1444. const { content } = compile(`
  1445. <script setup lang="ts">
  1446. interface Emits { (e: 'foo' | 'bar'): void }
  1447. const emit = defineEmits<Emits>()
  1448. </script>
  1449. `)
  1450. assertCode(content)
  1451. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1452. })
  1453. test('defineEmits w/ type (exported interface)', () => {
  1454. const { content } = compile(`
  1455. <script setup lang="ts">
  1456. export interface Emits { (e: 'foo' | 'bar'): void }
  1457. const emit = defineEmits<Emits>()
  1458. </script>
  1459. `)
  1460. assertCode(content)
  1461. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1462. })
  1463. test('defineEmits w/ type from normal script', () => {
  1464. const { content } = compile(`
  1465. <script lang="ts">
  1466. export interface Emits { (e: 'foo' | 'bar'): void }
  1467. </script>
  1468. <script setup lang="ts">
  1469. const emit = defineEmits<Emits>()
  1470. </script>
  1471. `)
  1472. assertCode(content)
  1473. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1474. })
  1475. test('defineEmits w/ type (type alias)', () => {
  1476. const { content } = compile(`
  1477. <script setup lang="ts">
  1478. type Emits = { (e: 'foo' | 'bar'): void }
  1479. const emit = defineEmits<Emits>()
  1480. </script>
  1481. `)
  1482. assertCode(content)
  1483. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1484. })
  1485. test('defineEmits w/ type (exported type alias)', () => {
  1486. const { content } = compile(`
  1487. <script setup lang="ts">
  1488. export type Emits = { (e: 'foo' | 'bar'): void }
  1489. const emit = defineEmits<Emits>()
  1490. </script>
  1491. `)
  1492. assertCode(content)
  1493. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1494. })
  1495. test('defineEmits w/ type (referenced function type)', () => {
  1496. const { content } = compile(`
  1497. <script setup lang="ts">
  1498. type Emits = (e: 'foo' | 'bar') => void
  1499. const emit = defineEmits<Emits>()
  1500. </script>
  1501. `)
  1502. assertCode(content)
  1503. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1504. })
  1505. test('defineEmits w/ type (referenced exported function type)', () => {
  1506. const { content } = compile(`
  1507. <script setup lang="ts">
  1508. export type Emits = (e: 'foo' | 'bar') => void
  1509. const emit = defineEmits<Emits>()
  1510. </script>
  1511. `)
  1512. assertCode(content)
  1513. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1514. })
  1515. // #5393
  1516. test('defineEmits w/ type (interface ts type)', () => {
  1517. const { content } = compile(`
  1518. <script setup lang="ts">
  1519. interface Emits { (e: 'foo'): void }
  1520. const emit: Emits = defineEmits(['foo'])
  1521. </script>
  1522. `)
  1523. assertCode(content)
  1524. expect(content).toMatch(`emits: ['foo']`)
  1525. })
  1526. test('defineEmits w/ type (property syntax)', () => {
  1527. const { content } = compile(`
  1528. <script setup lang="ts">
  1529. const emit = defineEmits<{ foo: [], bar: [] }>()
  1530. </script>
  1531. `)
  1532. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1533. assertCode(content)
  1534. })
  1535. describe('defineSlots()', () => {
  1536. test('basic usage', () => {
  1537. const { content } = compile(`
  1538. <script setup lang="ts">
  1539. const slots = defineSlots<{
  1540. default: { msg: string }
  1541. }>()
  1542. </script>
  1543. `)
  1544. assertCode(content)
  1545. expect(content).toMatch(`const slots = _useSlots()`)
  1546. expect(content).not.toMatch('defineSlots')
  1547. })
  1548. test('w/o return value', () => {
  1549. const { content } = compile(`
  1550. <script setup lang="ts">
  1551. defineSlots<{
  1552. default: { msg: string }
  1553. }>()
  1554. </script>
  1555. `)
  1556. assertCode(content)
  1557. expect(content).not.toMatch('defineSlots')
  1558. expect(content).not.toMatch(`_useSlots`)
  1559. })
  1560. test('w/o generic params', () => {
  1561. const { content } = compile(`
  1562. <script setup>
  1563. const slots = defineSlots()
  1564. </script>
  1565. `)
  1566. assertCode(content)
  1567. expect(content).toMatch(`const slots = _useSlots()`)
  1568. expect(content).not.toMatch('defineSlots')
  1569. })
  1570. })
  1571. test('runtime Enum', () => {
  1572. const { content, bindings } = compile(
  1573. `<script setup lang="ts">
  1574. enum Foo { A = 123 }
  1575. </script>`
  1576. )
  1577. assertCode(content)
  1578. expect(bindings).toStrictEqual({
  1579. Foo: BindingTypes.LITERAL_CONST
  1580. })
  1581. })
  1582. test('runtime Enum in normal script', () => {
  1583. const { content, bindings } = compile(
  1584. `<script lang="ts">
  1585. export enum D { D = "D" }
  1586. const enum C { C = "C" }
  1587. enum B { B = "B" }
  1588. </script>
  1589. <script setup lang="ts">
  1590. enum Foo { A = 123 }
  1591. </script>`
  1592. )
  1593. assertCode(content)
  1594. expect(bindings).toStrictEqual({
  1595. D: BindingTypes.LITERAL_CONST,
  1596. C: BindingTypes.LITERAL_CONST,
  1597. B: BindingTypes.LITERAL_CONST,
  1598. Foo: BindingTypes.LITERAL_CONST
  1599. })
  1600. })
  1601. test('const Enum', () => {
  1602. const { content, bindings } = compile(
  1603. `<script setup lang="ts">
  1604. const enum Foo { A = 123 }
  1605. </script>`,
  1606. { hoistStatic: true }
  1607. )
  1608. assertCode(content)
  1609. expect(bindings).toStrictEqual({
  1610. Foo: BindingTypes.LITERAL_CONST
  1611. })
  1612. })
  1613. test('runtime inference for Enum in defineProps', () => {
  1614. expect(
  1615. compile(
  1616. `<script setup lang="ts">
  1617. const enum Foo { A = 123 }
  1618. defineProps<{
  1619. foo: Foo
  1620. }>()
  1621. </script>`,
  1622. { hoistStatic: true }
  1623. ).content
  1624. ).toMatch(`foo: { type: Number`)
  1625. expect(
  1626. compile(
  1627. `<script setup lang="ts">
  1628. const enum Foo { A = '123' }
  1629. defineProps<{
  1630. foo: Foo
  1631. }>()
  1632. </script>`,
  1633. { hoistStatic: true }
  1634. ).content
  1635. ).toMatch(`foo: { type: String`)
  1636. expect(
  1637. compile(
  1638. `<script setup lang="ts">
  1639. const enum Foo { A = '123', B = 123 }
  1640. defineProps<{
  1641. foo: Foo
  1642. }>()
  1643. </script>`,
  1644. { hoistStatic: true }
  1645. ).content
  1646. ).toMatch(`foo: { type: [String, Number]`)
  1647. expect(
  1648. compile(
  1649. `<script setup lang="ts">
  1650. const enum Foo { A, B }
  1651. defineProps<{
  1652. foo: Foo
  1653. }>()
  1654. </script>`,
  1655. { hoistStatic: true }
  1656. ).content
  1657. ).toMatch(`foo: { type: Number`)
  1658. })
  1659. test('import type', () => {
  1660. const { content } = compile(
  1661. `<script setup lang="ts">
  1662. import type { Foo } from './main.ts'
  1663. import { type Bar, Baz } from './main.ts'
  1664. </script>`
  1665. )
  1666. expect(content).toMatch(`return { get Baz() { return Baz } }`)
  1667. assertCode(content)
  1668. })
  1669. })
  1670. describe('async/await detection', () => {
  1671. function assertAwaitDetection(code: string, shouldAsync = true) {
  1672. const { content } = compile(`<script setup>${code}</script>`, {
  1673. reactivityTransform: true
  1674. })
  1675. if (shouldAsync) {
  1676. expect(content).toMatch(`let __temp, __restore`)
  1677. }
  1678. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  1679. assertCode(content)
  1680. return content
  1681. }
  1682. test('expression statement', () => {
  1683. assertAwaitDetection(`await foo`)
  1684. })
  1685. test('variable', () => {
  1686. assertAwaitDetection(`const a = 1 + (await foo)`)
  1687. })
  1688. test('ref', () => {
  1689. assertAwaitDetection(`let a = $ref(1 + (await foo))`)
  1690. })
  1691. // #4448
  1692. test('nested await', () => {
  1693. assertAwaitDetection(`await (await foo)`)
  1694. assertAwaitDetection(`await ((await foo))`)
  1695. assertAwaitDetection(`await (await (await foo))`)
  1696. })
  1697. // should prepend semicolon
  1698. test('nested leading await in expression statement', () => {
  1699. const code = assertAwaitDetection(`foo()\nawait 1 + await 2`)
  1700. expect(code).toMatch(`foo()\n;(`)
  1701. })
  1702. // #4596 should NOT prepend semicolon
  1703. test('single line conditions', () => {
  1704. const code = assertAwaitDetection(`if (false) await foo()`)
  1705. expect(code).not.toMatch(`if (false) ;(`)
  1706. })
  1707. test('nested statements', () => {
  1708. assertAwaitDetection(`if (ok) { await foo } else { await bar }`)
  1709. })
  1710. test('multiple `if` nested statements', () => {
  1711. assertAwaitDetection(`if (ok) {
  1712. let a = 'foo'
  1713. await 0 + await 1
  1714. await 2
  1715. } else if (a) {
  1716. await 10
  1717. if (b) {
  1718. await 0 + await 1
  1719. } else {
  1720. let a = 'foo'
  1721. await 2
  1722. }
  1723. if (b) {
  1724. await 3
  1725. await 4
  1726. }
  1727. } else {
  1728. await 5
  1729. }`)
  1730. })
  1731. test('multiple `if while` nested statements', () => {
  1732. assertAwaitDetection(`if (ok) {
  1733. while (d) {
  1734. await 5
  1735. }
  1736. while (d) {
  1737. await 5
  1738. await 6
  1739. if (c) {
  1740. let f = 10
  1741. 10 + await 7
  1742. } else {
  1743. await 8
  1744. await 9
  1745. }
  1746. }
  1747. }`)
  1748. })
  1749. test('multiple `if for` nested statements', () => {
  1750. assertAwaitDetection(`if (ok) {
  1751. for (let a of [1,2,3]) {
  1752. await a
  1753. }
  1754. for (let a of [1,2,3]) {
  1755. await a
  1756. await a
  1757. }
  1758. }`)
  1759. })
  1760. test('should ignore await inside functions', () => {
  1761. // function declaration
  1762. assertAwaitDetection(`async function foo() { await bar }`, false)
  1763. // function expression
  1764. assertAwaitDetection(`const foo = async () => { await bar }`, false)
  1765. // object method
  1766. assertAwaitDetection(`const obj = { async method() { await bar }}`, false)
  1767. // class method
  1768. assertAwaitDetection(
  1769. `const cls = class Foo { async method() { await bar }}`,
  1770. false
  1771. )
  1772. })
  1773. })
  1774. describe('errors', () => {
  1775. test('<script> and <script setup> must have same lang', () => {
  1776. expect(() =>
  1777. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1778. ).toThrow(`<script> and <script setup> must have the same language type`)
  1779. })
  1780. const moduleErrorMsg = `cannot contain ES module exports`
  1781. test('non-type named exports', () => {
  1782. expect(() =>
  1783. compile(`<script setup>
  1784. export const a = 1
  1785. </script>`)
  1786. ).toThrow(moduleErrorMsg)
  1787. expect(() =>
  1788. compile(`<script setup>
  1789. export * from './foo'
  1790. </script>`)
  1791. ).toThrow(moduleErrorMsg)
  1792. expect(() =>
  1793. compile(`<script setup>
  1794. const bar = 1
  1795. export { bar as default }
  1796. </script>`)
  1797. ).toThrow(moduleErrorMsg)
  1798. })
  1799. test('defineProps/Emit() w/ both type and non-type args', () => {
  1800. expect(() => {
  1801. compile(`<script setup lang="ts">
  1802. defineProps<{}>({})
  1803. </script>`)
  1804. }).toThrow(`cannot accept both type and non-type arguments`)
  1805. expect(() => {
  1806. compile(`<script setup lang="ts">
  1807. defineEmits<{}>({})
  1808. </script>`)
  1809. }).toThrow(`cannot accept both type and non-type arguments`)
  1810. })
  1811. test('defineProps/Emit() referencing local var', () => {
  1812. expect(() =>
  1813. compile(`<script setup>
  1814. let bar = 1
  1815. defineProps({
  1816. foo: {
  1817. default: () => bar
  1818. }
  1819. })
  1820. </script>`)
  1821. ).toThrow(`cannot reference locally declared variables`)
  1822. expect(() =>
  1823. compile(`<script setup>
  1824. let bar = 'hello'
  1825. defineEmits([bar])
  1826. </script>`)
  1827. ).toThrow(`cannot reference locally declared variables`)
  1828. // #4644
  1829. expect(() =>
  1830. compile(`
  1831. <script>const bar = 1</script>
  1832. <script setup>
  1833. defineProps({
  1834. foo: {
  1835. default: () => bar
  1836. }
  1837. })
  1838. </script>`)
  1839. ).not.toThrow(`cannot reference locally declared variables`)
  1840. })
  1841. test('should allow defineProps/Emit() referencing scope var', () => {
  1842. assertCode(
  1843. compile(`<script setup>
  1844. const bar = 1
  1845. defineProps({
  1846. foo: {
  1847. default: bar => bar + 1
  1848. }
  1849. })
  1850. defineEmits({
  1851. foo: bar => bar > 1
  1852. })
  1853. </script>`).content
  1854. )
  1855. })
  1856. test('should allow defineProps/Emit() referencing imported binding', () => {
  1857. assertCode(
  1858. compile(`<script setup>
  1859. import { bar } from './bar'
  1860. defineProps({
  1861. foo: {
  1862. default: () => bar
  1863. }
  1864. })
  1865. defineEmits({
  1866. foo: () => bar > 1
  1867. })
  1868. </script>`).content
  1869. )
  1870. })
  1871. test('mixed usage of property / call signature in defineEmits', () => {
  1872. expect(() =>
  1873. compile(`<script setup lang="ts">
  1874. defineEmits<{
  1875. foo: []
  1876. (e: 'hi'): void
  1877. }>()
  1878. </script>`)
  1879. ).toThrow(
  1880. `defineEmits() type cannot mixed call signature and property syntax.`
  1881. )
  1882. })
  1883. })
  1884. })
  1885. describe('SFC analyze <script> bindings', () => {
  1886. it('can parse decorators syntax in typescript block', () => {
  1887. const { scriptAst } = compile(`
  1888. <script lang="ts">
  1889. import { Options, Vue } from 'vue-class-component';
  1890. @Options({
  1891. components: {
  1892. HelloWorld,
  1893. },
  1894. props: ['foo', 'bar']
  1895. })
  1896. export default class Home extends Vue {}
  1897. </script>
  1898. `)
  1899. expect(scriptAst).toBeDefined()
  1900. })
  1901. it('recognizes props array declaration', () => {
  1902. const { bindings } = compile(`
  1903. <script>
  1904. export default {
  1905. props: ['foo', 'bar']
  1906. }
  1907. </script>
  1908. `)
  1909. expect(bindings).toStrictEqual({
  1910. foo: BindingTypes.PROPS,
  1911. bar: BindingTypes.PROPS
  1912. })
  1913. expect(bindings!.__isScriptSetup).toBe(false)
  1914. })
  1915. it('recognizes props object declaration', () => {
  1916. const { bindings } = compile(`
  1917. <script>
  1918. export default {
  1919. props: {
  1920. foo: String,
  1921. bar: {
  1922. type: String,
  1923. },
  1924. baz: null,
  1925. qux: [String, Number]
  1926. }
  1927. }
  1928. </script>
  1929. `)
  1930. expect(bindings).toStrictEqual({
  1931. foo: BindingTypes.PROPS,
  1932. bar: BindingTypes.PROPS,
  1933. baz: BindingTypes.PROPS,
  1934. qux: BindingTypes.PROPS
  1935. })
  1936. expect(bindings!.__isScriptSetup).toBe(false)
  1937. })
  1938. it('recognizes setup return', () => {
  1939. const { bindings } = compile(`
  1940. <script>
  1941. const bar = 2
  1942. export default {
  1943. setup() {
  1944. return {
  1945. foo: 1,
  1946. bar
  1947. }
  1948. }
  1949. }
  1950. </script>
  1951. `)
  1952. expect(bindings).toStrictEqual({
  1953. foo: BindingTypes.SETUP_MAYBE_REF,
  1954. bar: BindingTypes.SETUP_MAYBE_REF
  1955. })
  1956. expect(bindings!.__isScriptSetup).toBe(false)
  1957. })
  1958. it('recognizes exported vars', () => {
  1959. const { bindings } = compile(`
  1960. <script>
  1961. export const foo = 2
  1962. </script>
  1963. <script setup>
  1964. console.log(foo)
  1965. </script>
  1966. `)
  1967. expect(bindings).toStrictEqual({
  1968. foo: BindingTypes.LITERAL_CONST
  1969. })
  1970. })
  1971. it('recognizes async setup return', () => {
  1972. const { bindings } = compile(`
  1973. <script>
  1974. const bar = 2
  1975. export default {
  1976. async setup() {
  1977. return {
  1978. foo: 1,
  1979. bar
  1980. }
  1981. }
  1982. }
  1983. </script>
  1984. `)
  1985. expect(bindings).toStrictEqual({
  1986. foo: BindingTypes.SETUP_MAYBE_REF,
  1987. bar: BindingTypes.SETUP_MAYBE_REF
  1988. })
  1989. expect(bindings!.__isScriptSetup).toBe(false)
  1990. })
  1991. it('recognizes data return', () => {
  1992. const { bindings } = compile(`
  1993. <script>
  1994. const bar = 2
  1995. export default {
  1996. data() {
  1997. return {
  1998. foo: null,
  1999. bar
  2000. }
  2001. }
  2002. }
  2003. </script>
  2004. `)
  2005. expect(bindings).toStrictEqual({
  2006. foo: BindingTypes.DATA,
  2007. bar: BindingTypes.DATA
  2008. })
  2009. })
  2010. it('recognizes methods', () => {
  2011. const { bindings } = compile(`
  2012. <script>
  2013. export default {
  2014. methods: {
  2015. foo() {}
  2016. }
  2017. }
  2018. </script>
  2019. `)
  2020. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  2021. })
  2022. it('recognizes computeds', () => {
  2023. const { bindings } = compile(`
  2024. <script>
  2025. export default {
  2026. computed: {
  2027. foo() {},
  2028. bar: {
  2029. get() {},
  2030. set() {},
  2031. }
  2032. }
  2033. }
  2034. </script>
  2035. `)
  2036. expect(bindings).toStrictEqual({
  2037. foo: BindingTypes.OPTIONS,
  2038. bar: BindingTypes.OPTIONS
  2039. })
  2040. })
  2041. it('recognizes injections array declaration', () => {
  2042. const { bindings } = compile(`
  2043. <script>
  2044. export default {
  2045. inject: ['foo', 'bar']
  2046. }
  2047. </script>
  2048. `)
  2049. expect(bindings).toStrictEqual({
  2050. foo: BindingTypes.OPTIONS,
  2051. bar: BindingTypes.OPTIONS
  2052. })
  2053. })
  2054. it('recognizes injections object declaration', () => {
  2055. const { bindings } = compile(`
  2056. <script>
  2057. export default {
  2058. inject: {
  2059. foo: {},
  2060. bar: {},
  2061. }
  2062. }
  2063. </script>
  2064. `)
  2065. expect(bindings).toStrictEqual({
  2066. foo: BindingTypes.OPTIONS,
  2067. bar: BindingTypes.OPTIONS
  2068. })
  2069. })
  2070. it('works for mixed bindings', () => {
  2071. const { bindings } = compile(`
  2072. <script>
  2073. export default {
  2074. inject: ['foo'],
  2075. props: {
  2076. bar: String,
  2077. },
  2078. setup() {
  2079. return {
  2080. baz: null,
  2081. }
  2082. },
  2083. data() {
  2084. return {
  2085. qux: null
  2086. }
  2087. },
  2088. methods: {
  2089. quux() {}
  2090. },
  2091. computed: {
  2092. quuz() {}
  2093. }
  2094. }
  2095. </script>
  2096. `)
  2097. expect(bindings).toStrictEqual({
  2098. foo: BindingTypes.OPTIONS,
  2099. bar: BindingTypes.PROPS,
  2100. baz: BindingTypes.SETUP_MAYBE_REF,
  2101. qux: BindingTypes.DATA,
  2102. quux: BindingTypes.OPTIONS,
  2103. quuz: BindingTypes.OPTIONS
  2104. })
  2105. })
  2106. it('works for script setup', () => {
  2107. const { bindings } = compile(`
  2108. <script setup>
  2109. import { ref as r } from 'vue'
  2110. defineProps({
  2111. foo: String
  2112. })
  2113. const a = r(1)
  2114. let b = 2
  2115. const c = 3
  2116. const { d } = someFoo()
  2117. let { e } = someBar()
  2118. </script>
  2119. `)
  2120. expect(bindings).toStrictEqual({
  2121. r: BindingTypes.SETUP_CONST,
  2122. a: BindingTypes.SETUP_REF,
  2123. b: BindingTypes.SETUP_LET,
  2124. c: BindingTypes.LITERAL_CONST,
  2125. d: BindingTypes.SETUP_MAYBE_REF,
  2126. e: BindingTypes.SETUP_LET,
  2127. foo: BindingTypes.PROPS
  2128. })
  2129. })
  2130. describe('auto name inference', () => {
  2131. test('basic', () => {
  2132. const { content } = compile(
  2133. `<script setup>const a = 1</script>
  2134. <template>{{ a }}</template>`,
  2135. undefined,
  2136. {
  2137. filename: 'FooBar.vue'
  2138. }
  2139. )
  2140. expect(content).toMatch(`export default {
  2141. __name: 'FooBar'`)
  2142. assertCode(content)
  2143. })
  2144. test('do not overwrite manual name (object)', () => {
  2145. const { content } = compile(
  2146. `<script>
  2147. export default {
  2148. name: 'Baz'
  2149. }
  2150. </script>
  2151. <script setup>const a = 1</script>
  2152. <template>{{ a }}</template>`,
  2153. undefined,
  2154. {
  2155. filename: 'FooBar.vue'
  2156. }
  2157. )
  2158. expect(content).not.toMatch(`name: 'FooBar'`)
  2159. expect(content).toMatch(`name: 'Baz'`)
  2160. assertCode(content)
  2161. })
  2162. test('do not overwrite manual name (call)', () => {
  2163. const { content } = compile(
  2164. `<script>
  2165. import { defineComponent } from 'vue'
  2166. export default defineComponent({
  2167. name: 'Baz'
  2168. })
  2169. </script>
  2170. <script setup>const a = 1</script>
  2171. <template>{{ a }}</template>`,
  2172. undefined,
  2173. {
  2174. filename: 'FooBar.vue'
  2175. }
  2176. )
  2177. expect(content).not.toMatch(`name: 'FooBar'`)
  2178. expect(content).toMatch(`name: 'Baz'`)
  2179. assertCode(content)
  2180. })
  2181. })
  2182. })
  2183. describe('SFC genDefaultAs', () => {
  2184. test('normal <script> only', () => {
  2185. const { content } = compile(
  2186. `<script>
  2187. export default {}
  2188. </script>`,
  2189. {
  2190. genDefaultAs: '_sfc_'
  2191. }
  2192. )
  2193. expect(content).not.toMatch('export default')
  2194. expect(content).toMatch(`const _sfc_ = {}`)
  2195. assertCode(content)
  2196. })
  2197. test('normal <script> w/ cssVars', () => {
  2198. const { content } = compile(
  2199. `<script>
  2200. export default {}
  2201. </script>
  2202. <style>
  2203. .foo { color: v-bind(x) }
  2204. </style>`,
  2205. {
  2206. genDefaultAs: '_sfc_'
  2207. }
  2208. )
  2209. expect(content).not.toMatch('export default')
  2210. expect(content).not.toMatch('__default__')
  2211. expect(content).toMatch(`const _sfc_ = {}`)
  2212. assertCode(content)
  2213. })
  2214. test('<script> + <script setup>', () => {
  2215. const { content } = compile(
  2216. `<script>
  2217. export default {}
  2218. </script>
  2219. <script setup>
  2220. const a = 1
  2221. </script>`,
  2222. {
  2223. genDefaultAs: '_sfc_'
  2224. }
  2225. )
  2226. expect(content).not.toMatch('export default')
  2227. expect(content).toMatch(
  2228. `const _sfc_ = /*#__PURE__*/Object.assign(__default__`
  2229. )
  2230. assertCode(content)
  2231. })
  2232. test('<script> + <script setup>', () => {
  2233. const { content } = compile(
  2234. `<script>
  2235. export default {}
  2236. </script>
  2237. <script setup>
  2238. const a = 1
  2239. </script>`,
  2240. {
  2241. genDefaultAs: '_sfc_'
  2242. }
  2243. )
  2244. expect(content).not.toMatch('export default')
  2245. expect(content).toMatch(
  2246. `const _sfc_ = /*#__PURE__*/Object.assign(__default__`
  2247. )
  2248. assertCode(content)
  2249. })
  2250. test('<script setup> only', () => {
  2251. const { content } = compile(
  2252. `<script setup>
  2253. const a = 1
  2254. </script>`,
  2255. {
  2256. genDefaultAs: '_sfc_'
  2257. }
  2258. )
  2259. expect(content).not.toMatch('export default')
  2260. expect(content).toMatch(`const _sfc_ = {\n setup`)
  2261. assertCode(content)
  2262. })
  2263. test('<script setup> only w/ ts', () => {
  2264. const { content } = compile(
  2265. `<script setup lang="ts">
  2266. const a = 1
  2267. </script>`,
  2268. {
  2269. genDefaultAs: '_sfc_'
  2270. }
  2271. )
  2272. expect(content).not.toMatch('export default')
  2273. expect(content).toMatch(`const _sfc_ = /*#__PURE__*/_defineComponent(`)
  2274. assertCode(content)
  2275. })
  2276. test('<script> + <script setup> w/ ts', () => {
  2277. const { content } = compile(
  2278. `<script lang="ts">
  2279. export default {}
  2280. </script>
  2281. <script setup lang="ts">
  2282. const a = 1
  2283. </script>`,
  2284. {
  2285. genDefaultAs: '_sfc_'
  2286. }
  2287. )
  2288. expect(content).not.toMatch('export default')
  2289. expect(content).toMatch(
  2290. `const _sfc_ = /*#__PURE__*/_defineComponent({\n ...__default__`
  2291. )
  2292. assertCode(content)
  2293. })
  2294. })