compileScript.spec.ts 59 KB

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