compileScript.spec.ts 57 KB

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