compileScript.spec.ts 56 KB

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