compileScript.spec.ts 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import { compileSFCScript as compile, assertCode } from './utils'
  3. describe('SFC compile <script setup>', () => {
  4. test('should expose top level declarations', () => {
  5. const { content } = 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. `)
  14. assertCode(content)
  15. expect(content).toMatch('return { a, b, c, d, x }')
  16. })
  17. test('defineProps()', () => {
  18. const { content, bindings } = compile(`
  19. <script setup>
  20. const props = defineProps({
  21. foo: String
  22. })
  23. const bar = 1
  24. </script>
  25. `)
  26. // should generate working code
  27. assertCode(content)
  28. // should anayze bindings
  29. expect(bindings).toStrictEqual({
  30. foo: BindingTypes.PROPS,
  31. bar: BindingTypes.SETUP_CONST,
  32. props: BindingTypes.SETUP_CONST
  33. })
  34. // should remove defineOptions import and call
  35. expect(content).not.toMatch('defineProps')
  36. // should generate correct setup signature
  37. expect(content).toMatch(`setup(__props, { expose }) {`)
  38. // should assign user identifier to it
  39. expect(content).toMatch(`const props = __props`)
  40. // should include context options in default export
  41. expect(content).toMatch(`export default {
  42. props: {
  43. foo: String
  44. },`)
  45. })
  46. test('defineProps w/ external definition', () => {
  47. const { content } = compile(`
  48. <script setup>
  49. import { propsModel } from './props'
  50. const props = defineProps(propsModel)
  51. </script>
  52. `)
  53. assertCode(content)
  54. expect(content).toMatch(`export default {
  55. props: propsModel,`)
  56. })
  57. test('defineEmits()', () => {
  58. const { content, bindings } = compile(`
  59. <script setup>
  60. const myEmit = defineEmits(['foo', 'bar'])
  61. </script>
  62. `)
  63. assertCode(content)
  64. expect(bindings).toStrictEqual({
  65. myEmit: BindingTypes.SETUP_CONST
  66. })
  67. // should remove defineOptions import and call
  68. expect(content).not.toMatch('defineEmits')
  69. // should generate correct setup signature
  70. expect(content).toMatch(`setup(__props, { expose, emit: myEmit }) {`)
  71. // should include context options in default export
  72. expect(content).toMatch(`export default {
  73. emits: ['foo', 'bar'],`)
  74. })
  75. test('defineProps/defineEmits in multi-variable decalration', () => {
  76. const { content } = compile(`
  77. <script setup>
  78. const props = defineProps(['item']),
  79. a = 1,
  80. emit = defineEmits(['a']);
  81. </script>
  82. `)
  83. assertCode(content)
  84. expect(content).toMatch(`const a = 1;`) // test correct removal
  85. expect(content).toMatch(`props: ['item'],`)
  86. expect(content).toMatch(`emits: ['a'],`)
  87. })
  88. test('defineProps/defineEmits in multi-variable decalration (full removal)', () => {
  89. const { content } = compile(`
  90. <script setup>
  91. const props = defineProps(['item']),
  92. emit = defineEmits(['a']);
  93. </script>
  94. `)
  95. assertCode(content)
  96. expect(content).toMatch(`props: ['item'],`)
  97. expect(content).toMatch(`emits: ['a'],`)
  98. })
  99. test('defineExpose()', () => {
  100. const { content } = compile(`
  101. <script setup>
  102. defineExpose({ foo: 123 })
  103. </script>
  104. `)
  105. assertCode(content)
  106. // should remove defineOptions import and call
  107. expect(content).not.toMatch('defineExpose')
  108. // should generate correct setup signature
  109. expect(content).toMatch(`setup(__props, { expose }) {`)
  110. // should replace callee
  111. expect(content).toMatch(/\bexpose\(\{ foo: 123 \}\)/)
  112. })
  113. describe('<script> and <script setup> co-usage', () => {
  114. test('script first', () => {
  115. const { content } = compile(`
  116. <script>
  117. export const n = 1
  118. </script>
  119. <script setup>
  120. import { x } from './x'
  121. x()
  122. </script>
  123. `)
  124. assertCode(content)
  125. })
  126. test('script setup first', () => {
  127. const { content } = compile(`
  128. <script setup>
  129. import { x } from './x'
  130. x()
  131. </script>
  132. <script>
  133. export const n = 1
  134. </script>
  135. `)
  136. assertCode(content)
  137. })
  138. })
  139. describe('imports', () => {
  140. test('should hoist and expose imports', () => {
  141. assertCode(
  142. compile(`<script setup>
  143. import { ref } from 'vue'
  144. import 'foo/css'
  145. </script>`).content
  146. )
  147. })
  148. test('should extract comment for import or type declarations', () => {
  149. assertCode(
  150. compile(`
  151. <script setup>
  152. import a from 'a' // comment
  153. import b from 'b'
  154. </script>
  155. `).content
  156. )
  157. })
  158. // #2740
  159. test('should allow defineProps/Emit at the start of imports', () => {
  160. assertCode(
  161. compile(`<script setup>
  162. import { ref } from 'vue'
  163. defineProps(['foo'])
  164. defineEmits(['bar'])
  165. const r = ref(0)
  166. </script>`).content
  167. )
  168. })
  169. test('dedupe between user & helper', () => {
  170. const { content } = compile(
  171. `
  172. <script setup>
  173. import { ref } from 'vue'
  174. let foo = $ref(1)
  175. </script>
  176. `,
  177. { refSugar: true }
  178. )
  179. assertCode(content)
  180. expect(content).toMatch(`import { ref } from 'vue'`)
  181. })
  182. test('import dedupe between <script> and <script setup>', () => {
  183. const { content } = compile(`
  184. <script>
  185. import { x } from './x'
  186. </script>
  187. <script setup>
  188. import { x } from './x'
  189. x()
  190. </script>
  191. `)
  192. assertCode(content)
  193. expect(content.indexOf(`import { x }`)).toEqual(
  194. content.lastIndexOf(`import { x }`)
  195. )
  196. })
  197. })
  198. describe('inlineTemplate mode', () => {
  199. test('should work', () => {
  200. const { content } = compile(
  201. `
  202. <script setup>
  203. import { ref } from 'vue'
  204. const count = ref(0)
  205. </script>
  206. <template>
  207. <div>{{ count }}</div>
  208. <div>static</div>
  209. </template>
  210. `,
  211. { inlineTemplate: true }
  212. )
  213. // check snapshot and make sure helper imports and
  214. // hoists are placed correctly.
  215. assertCode(content)
  216. // in inline mode, no need to call expose() since nothing is exposed
  217. // anyway!
  218. expect(content).not.toMatch(`expose()`)
  219. })
  220. test('with defineExpose()', () => {
  221. const { content } = compile(
  222. `
  223. <script setup>
  224. const count = ref(0)
  225. defineExpose({ count })
  226. </script>
  227. `,
  228. { inlineTemplate: true }
  229. )
  230. assertCode(content)
  231. expect(content).toMatch(`setup(__props, { expose })`)
  232. expect(content).toMatch(`expose({ count })`)
  233. })
  234. test('referencing scope components and directives', () => {
  235. const { content } = compile(
  236. `
  237. <script setup>
  238. import ChildComp from './Child.vue'
  239. import SomeOtherComp from './Other.vue'
  240. import vMyDir from './my-dir'
  241. </script>
  242. <template>
  243. <div v-my-dir></div>
  244. <ChildComp/>
  245. <some-other-comp/>
  246. </template>
  247. `,
  248. { inlineTemplate: true }
  249. )
  250. expect(content).toMatch('[_unref(vMyDir)]')
  251. expect(content).toMatch('_createVNode(ChildComp)')
  252. // kebab-case component support
  253. expect(content).toMatch('_createVNode(SomeOtherComp)')
  254. assertCode(content)
  255. })
  256. test('avoid unref() when necessary', () => {
  257. // function, const, component import
  258. const { content } = compile(
  259. `<script setup>
  260. import { ref } from 'vue'
  261. import Foo, { bar } from './Foo.vue'
  262. import other from './util'
  263. const count = ref(0)
  264. const constant = {}
  265. const maybe = foo()
  266. let lett = 1
  267. function fn() {}
  268. </script>
  269. <template>
  270. <Foo>{{ bar }}</Foo>
  271. <div @click="fn">{{ count }} {{ constant }} {{ maybe }} {{ lett }} {{ other }}</div>
  272. </template>
  273. `,
  274. { inlineTemplate: true }
  275. )
  276. // no need to unref vue component import
  277. expect(content).toMatch(`createVNode(Foo,`)
  278. // #2699 should unref named imports from .vue
  279. expect(content).toMatch(`unref(bar)`)
  280. // should unref other imports
  281. expect(content).toMatch(`unref(other)`)
  282. // no need to unref constant literals
  283. expect(content).not.toMatch(`unref(constant)`)
  284. // should directly use .value for known refs
  285. expect(content).toMatch(`count.value`)
  286. // should unref() on const bindings that may be refs
  287. expect(content).toMatch(`unref(maybe)`)
  288. // should unref() on let bindings
  289. expect(content).toMatch(`unref(lett)`)
  290. // no need to unref function declarations
  291. expect(content).toMatch(`{ onClick: fn }`)
  292. // no need to mark constant fns in patch flag
  293. expect(content).not.toMatch(`PROPS`)
  294. assertCode(content)
  295. })
  296. test('v-model codegen', () => {
  297. const { content } = compile(
  298. `<script setup>
  299. import { ref } from 'vue'
  300. const count = ref(0)
  301. const maybe = foo()
  302. let lett = 1
  303. </script>
  304. <template>
  305. <input v-model="count">
  306. <input v-model="maybe">
  307. <input v-model="lett">
  308. </template>
  309. `,
  310. { inlineTemplate: true }
  311. )
  312. // known const ref: set value
  313. expect(content).toMatch(`count.value = $event`)
  314. // const but maybe ref: also assign .value directly since non-ref
  315. // won't work
  316. expect(content).toMatch(`maybe.value = $event`)
  317. // let: handle both cases
  318. expect(content).toMatch(
  319. `_isRef(lett) ? lett.value = $event : lett = $event`
  320. )
  321. assertCode(content)
  322. })
  323. test('template assignment expression codegen', () => {
  324. const { content } = compile(
  325. `<script setup>
  326. import { ref } from 'vue'
  327. const count = ref(0)
  328. const maybe = foo()
  329. let lett = 1
  330. let v = ref(1)
  331. </script>
  332. <template>
  333. <div @click="count = 1"/>
  334. <div @click="maybe = count"/>
  335. <div @click="lett = count"/>
  336. <div @click="v += 1"/>
  337. <div @click="v -= 1"/>
  338. </template>
  339. `,
  340. { inlineTemplate: true }
  341. )
  342. // known const ref: set value
  343. expect(content).toMatch(`count.value = 1`)
  344. // const but maybe ref: only assign after check
  345. expect(content).toMatch(`maybe.value = count.value`)
  346. // let: handle both cases
  347. expect(content).toMatch(
  348. `_isRef(lett) ? lett.value = count.value : lett = count.value`
  349. )
  350. expect(content).toMatch(`_isRef(v) ? v.value += 1 : v += 1`)
  351. expect(content).toMatch(`_isRef(v) ? v.value -= 1 : v -= 1`)
  352. assertCode(content)
  353. })
  354. test('template update expression codegen', () => {
  355. const { content } = compile(
  356. `<script setup>
  357. import { ref } from 'vue'
  358. const count = ref(0)
  359. const maybe = foo()
  360. let lett = 1
  361. </script>
  362. <template>
  363. <div @click="count++"/>
  364. <div @click="--count"/>
  365. <div @click="maybe++"/>
  366. <div @click="--maybe"/>
  367. <div @click="lett++"/>
  368. <div @click="--lett"/>
  369. </template>
  370. `,
  371. { inlineTemplate: true }
  372. )
  373. // known const ref: set value
  374. expect(content).toMatch(`count.value++`)
  375. expect(content).toMatch(`--count.value`)
  376. // const but maybe ref (non-ref case ignored)
  377. expect(content).toMatch(`maybe.value++`)
  378. expect(content).toMatch(`--maybe.value`)
  379. // let: handle both cases
  380. expect(content).toMatch(`_isRef(lett) ? lett.value++ : lett++`)
  381. expect(content).toMatch(`_isRef(lett) ? --lett.value : --lett`)
  382. assertCode(content)
  383. })
  384. test('template destructure assignment codegen', () => {
  385. const { content } = compile(
  386. `<script setup>
  387. import { ref } from 'vue'
  388. const val = {}
  389. const count = ref(0)
  390. const maybe = foo()
  391. let lett = 1
  392. </script>
  393. <template>
  394. <div @click="({ count } = val)"/>
  395. <div @click="[maybe] = val"/>
  396. <div @click="({ lett } = val)"/>
  397. </template>
  398. `,
  399. { inlineTemplate: true }
  400. )
  401. // known const ref: set value
  402. expect(content).toMatch(`({ count: count.value } = val)`)
  403. // const but maybe ref (non-ref case ignored)
  404. expect(content).toMatch(`[maybe.value] = val`)
  405. // let: assumes non-ref
  406. expect(content).toMatch(`{ lett: lett } = val`)
  407. assertCode(content)
  408. })
  409. test('ssr codegen', () => {
  410. const { content } = compile(
  411. `
  412. <script setup>
  413. import { ref } from 'vue'
  414. const count = ref(0)
  415. </script>
  416. <template>
  417. <div>{{ count }}</div>
  418. <div>static</div>
  419. </template>
  420. <style>
  421. div { color: v-bind(count) }
  422. </style>
  423. `,
  424. {
  425. inlineTemplate: true,
  426. templateOptions: {
  427. ssr: true
  428. }
  429. }
  430. )
  431. expect(content).toMatch(`\n __ssrInlineRender: true,\n`)
  432. expect(content).toMatch(`return (_ctx, _push`)
  433. expect(content).toMatch(`ssrInterpolate`)
  434. assertCode(content)
  435. })
  436. })
  437. describe('with TypeScript', () => {
  438. test('hoist type declarations', () => {
  439. const { content } = compile(`
  440. <script setup lang="ts">
  441. export interface Foo {}
  442. type Bar = {}
  443. </script>`)
  444. assertCode(content)
  445. })
  446. test('defineProps/Emit w/ runtime options', () => {
  447. const { content } = compile(`
  448. <script setup lang="ts">
  449. const props = defineProps({ foo: String })
  450. const emit = defineEmits(['a', 'b'])
  451. </script>
  452. `)
  453. assertCode(content)
  454. expect(content).toMatch(`export default _defineComponent({
  455. props: { foo: String },
  456. emits: ['a', 'b'],
  457. setup(__props, { expose, emit }) {`)
  458. })
  459. test('defineProps w/ type', () => {
  460. const { content, bindings } = compile(`
  461. <script setup lang="ts">
  462. interface Test {}
  463. type Alias = number[]
  464. defineProps<{
  465. string: string
  466. number: number
  467. boolean: boolean
  468. object: object
  469. objectLiteral: { a: number }
  470. fn: (n: number) => void
  471. functionRef: Function
  472. objectRef: Object
  473. array: string[]
  474. arrayRef: Array<any>
  475. tuple: [number, number]
  476. set: Set<string>
  477. literal: 'foo'
  478. optional?: any
  479. recordRef: Record<string, null>
  480. interface: Test
  481. alias: Alias
  482. method(): void
  483. union: string | number
  484. literalUnion: 'foo' | 'bar'
  485. literalUnionMixed: 'foo' | 1 | boolean
  486. intersection: Test & {}
  487. foo: ((item: any) => boolean) | null
  488. }>()
  489. </script>`)
  490. assertCode(content)
  491. expect(content).toMatch(`string: { type: String, required: true }`)
  492. expect(content).toMatch(`number: { type: Number, required: true }`)
  493. expect(content).toMatch(`boolean: { type: Boolean, required: true }`)
  494. expect(content).toMatch(`object: { type: Object, required: true }`)
  495. expect(content).toMatch(`objectLiteral: { type: Object, required: true }`)
  496. expect(content).toMatch(`fn: { type: Function, required: true }`)
  497. expect(content).toMatch(`functionRef: { type: Function, required: true }`)
  498. expect(content).toMatch(`objectRef: { type: Object, required: true }`)
  499. expect(content).toMatch(`array: { type: Array, required: true }`)
  500. expect(content).toMatch(`arrayRef: { type: Array, required: true }`)
  501. expect(content).toMatch(`tuple: { type: Array, required: true }`)
  502. expect(content).toMatch(`set: { type: Set, required: true }`)
  503. expect(content).toMatch(`literal: { type: String, required: true }`)
  504. expect(content).toMatch(`optional: { type: null, required: false }`)
  505. expect(content).toMatch(`recordRef: { type: Object, required: true }`)
  506. expect(content).toMatch(`interface: { type: Object, required: true }`)
  507. expect(content).toMatch(`alias: { type: Array, required: true }`)
  508. expect(content).toMatch(`method: { type: Function, required: true }`)
  509. expect(content).toMatch(
  510. `union: { type: [String, Number], required: true }`
  511. )
  512. expect(content).toMatch(
  513. `literalUnion: { type: [String, String], required: true }`
  514. )
  515. expect(content).toMatch(
  516. `literalUnionMixed: { type: [String, Number, Boolean], required: true }`
  517. )
  518. expect(content).toMatch(`intersection: { type: Object, required: true }`)
  519. expect(content).toMatch(`foo: { type: [Function, null], required: true }`)
  520. expect(bindings).toStrictEqual({
  521. string: BindingTypes.PROPS,
  522. number: BindingTypes.PROPS,
  523. boolean: BindingTypes.PROPS,
  524. object: BindingTypes.PROPS,
  525. objectLiteral: BindingTypes.PROPS,
  526. fn: BindingTypes.PROPS,
  527. functionRef: BindingTypes.PROPS,
  528. objectRef: BindingTypes.PROPS,
  529. array: BindingTypes.PROPS,
  530. arrayRef: BindingTypes.PROPS,
  531. tuple: BindingTypes.PROPS,
  532. set: BindingTypes.PROPS,
  533. literal: BindingTypes.PROPS,
  534. optional: BindingTypes.PROPS,
  535. recordRef: BindingTypes.PROPS,
  536. interface: BindingTypes.PROPS,
  537. alias: BindingTypes.PROPS,
  538. method: BindingTypes.PROPS,
  539. union: BindingTypes.PROPS,
  540. literalUnion: BindingTypes.PROPS,
  541. literalUnionMixed: BindingTypes.PROPS,
  542. intersection: BindingTypes.PROPS,
  543. foo: BindingTypes.PROPS
  544. })
  545. })
  546. test('defineProps w/ interface', () => {
  547. const { content, bindings } = compile(`
  548. <script setup lang="ts">
  549. interface Props { x?: number }
  550. defineProps<Props>()
  551. </script>
  552. `)
  553. assertCode(content)
  554. expect(content).toMatch(`x: { type: Number, required: false }`)
  555. expect(bindings).toStrictEqual({
  556. x: BindingTypes.PROPS
  557. })
  558. })
  559. test('defineProps w/ exported interface', () => {
  560. const { content, bindings } = compile(`
  561. <script setup lang="ts">
  562. export interface Props { x?: number }
  563. defineProps<Props>()
  564. </script>
  565. `)
  566. assertCode(content)
  567. expect(content).toMatch(`x: { type: Number, required: false }`)
  568. expect(bindings).toStrictEqual({
  569. x: BindingTypes.PROPS
  570. })
  571. })
  572. test('defineProps w/ type alias', () => {
  573. const { content, bindings } = compile(`
  574. <script setup lang="ts">
  575. type Props = { x?: number }
  576. defineProps<Props>()
  577. </script>
  578. `)
  579. assertCode(content)
  580. expect(content).toMatch(`x: { type: Number, required: false }`)
  581. expect(bindings).toStrictEqual({
  582. x: BindingTypes.PROPS
  583. })
  584. })
  585. test('defineProps w/ exported type alias', () => {
  586. const { content, bindings } = compile(`
  587. <script setup lang="ts">
  588. export type Props = { x?: number }
  589. defineProps<Props>()
  590. </script>
  591. `)
  592. assertCode(content)
  593. expect(content).toMatch(`x: { type: Number, required: false }`)
  594. expect(bindings).toStrictEqual({
  595. x: BindingTypes.PROPS
  596. })
  597. })
  598. test('withDefaults (static)', () => {
  599. const { content, bindings } = compile(`
  600. <script setup lang="ts">
  601. const props = withDefaults(defineProps<{
  602. foo?: string
  603. bar?: number
  604. }>(), {
  605. foo: 'hi'
  606. })
  607. </script>
  608. `)
  609. assertCode(content)
  610. expect(content).toMatch(
  611. `foo: { type: String, required: false, default: 'hi' }`
  612. )
  613. expect(content).toMatch(`bar: { type: Number, required: false }`)
  614. expect(content).toMatch(`const props = __props`)
  615. expect(bindings).toStrictEqual({
  616. foo: BindingTypes.PROPS,
  617. bar: BindingTypes.PROPS,
  618. props: BindingTypes.SETUP_CONST
  619. })
  620. })
  621. test('withDefaults (dynamic)', () => {
  622. const { content } = compile(`
  623. <script setup lang="ts">
  624. import { defaults } from './foo'
  625. const props = withDefaults(defineProps<{
  626. foo?: string
  627. bar?: number
  628. }>(), { ...defaults })
  629. </script>
  630. `)
  631. assertCode(content)
  632. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  633. expect(content).toMatch(
  634. `
  635. _mergeDefaults({
  636. foo: { type: String, required: false },
  637. bar: { type: Number, required: false }
  638. }, { ...defaults })`.trim()
  639. )
  640. })
  641. test('defineEmits w/ type', () => {
  642. const { content } = compile(`
  643. <script setup lang="ts">
  644. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  645. </script>
  646. `)
  647. assertCode(content)
  648. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  649. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  650. })
  651. test('defineEmits w/ type (union)', () => {
  652. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  653. expect(() =>
  654. compile(`
  655. <script setup lang="ts">
  656. const emit = defineEmits<${type}>()
  657. </script>
  658. `)
  659. ).toThrow()
  660. })
  661. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  662. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  663. const { content } = compile(`
  664. <script setup lang="ts">
  665. const emit = defineEmits<${type}>()
  666. </script>
  667. `)
  668. assertCode(content)
  669. expect(content).toMatch(`emit: (${type}),`)
  670. expect(content).toMatch(
  671. `emits: ["foo", "bar", "baz"] as unknown as undefined`
  672. )
  673. })
  674. test('defineEmits w/ type (interface)', () => {
  675. const { content } = compile(`
  676. <script setup lang="ts">
  677. interface Emits { (e: 'foo' | 'bar'): void }
  678. const emit = defineEmits<Emits>()
  679. </script>
  680. `)
  681. assertCode(content)
  682. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  683. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  684. })
  685. test('defineEmits w/ type (exported interface)', () => {
  686. const { content } = compile(`
  687. <script setup lang="ts">
  688. export interface Emits { (e: 'foo' | 'bar'): void }
  689. const emit = defineEmits<Emits>()
  690. </script>
  691. `)
  692. assertCode(content)
  693. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  694. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  695. })
  696. test('defineEmits w/ type (type alias)', () => {
  697. const { content } = compile(`
  698. <script setup lang="ts">
  699. type Emits = { (e: 'foo' | 'bar'): void }
  700. const emit = defineEmits<Emits>()
  701. </script>
  702. `)
  703. assertCode(content)
  704. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  705. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  706. })
  707. test('defineEmits w/ type (exported type alias)', () => {
  708. const { content } = compile(`
  709. <script setup lang="ts">
  710. export type Emits = { (e: 'foo' | 'bar'): void }
  711. const emit = defineEmits<Emits>()
  712. </script>
  713. `)
  714. assertCode(content)
  715. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  716. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  717. })
  718. test('defineEmits w/ type (referenced function type)', () => {
  719. const { content } = compile(`
  720. <script setup lang="ts">
  721. type Emits = (e: 'foo' | 'bar') => void
  722. const emit = defineEmits<Emits>()
  723. </script>
  724. `)
  725. assertCode(content)
  726. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  727. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  728. })
  729. test('defineEmits w/ type (referenced exported function type)', () => {
  730. const { content } = compile(`
  731. <script setup lang="ts">
  732. export type Emits = (e: 'foo' | 'bar') => void
  733. const emit = defineEmits<Emits>()
  734. </script>
  735. `)
  736. assertCode(content)
  737. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  738. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  739. })
  740. test('runtime Enum', () => {
  741. const { content, bindings } = compile(
  742. `<script setup lang="ts">
  743. enum Foo { A = 123 }
  744. </script>`
  745. )
  746. assertCode(content)
  747. expect(bindings).toStrictEqual({
  748. Foo: BindingTypes.SETUP_CONST
  749. })
  750. })
  751. })
  752. describe('async/await detection', () => {
  753. function assertAwaitDetection(
  754. code: string,
  755. expected: string | ((content: string) => boolean),
  756. shouldAsync = true
  757. ) {
  758. const { content } = compile(`<script setup>${code}</script>`, {
  759. refSugar: true
  760. })
  761. if (shouldAsync) {
  762. expect(content).toMatch(`let __temp, __restore`)
  763. }
  764. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  765. if (typeof expected === 'string') {
  766. expect(content).toMatch(expected)
  767. } else {
  768. expect(expected(content)).toBe(true)
  769. }
  770. }
  771. test('expression statement', () => {
  772. assertAwaitDetection(
  773. `await foo`,
  774. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  775. )
  776. })
  777. test('variable', () => {
  778. assertAwaitDetection(
  779. `const a = 1 + (await foo)`,
  780. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  781. )
  782. })
  783. test('ref', () => {
  784. assertAwaitDetection(
  785. `let a = $ref(1 + (await foo))`,
  786. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  787. )
  788. })
  789. test('nested statements', () => {
  790. assertAwaitDetection(`if (ok) { await foo } else { await bar }`, code => {
  791. return (
  792. code.includes(
  793. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  794. ) &&
  795. code.includes(
  796. `;(([__temp,__restore]=_withAsyncContext(()=>(bar))),__temp=await __temp,__restore())`
  797. )
  798. )
  799. })
  800. })
  801. test('should ignore await inside functions', () => {
  802. // function declaration
  803. assertAwaitDetection(
  804. `async function foo() { await bar }`,
  805. `await bar`,
  806. false
  807. )
  808. // function expression
  809. assertAwaitDetection(
  810. `const foo = async () => { await bar }`,
  811. `await bar`,
  812. false
  813. )
  814. // object method
  815. assertAwaitDetection(
  816. `const obj = { async method() { await bar }}`,
  817. `await bar`,
  818. false
  819. )
  820. // class method
  821. assertAwaitDetection(
  822. `const cls = class Foo { async method() { await bar }}`,
  823. `await bar`,
  824. false
  825. )
  826. })
  827. })
  828. describe('errors', () => {
  829. test('<script> and <script setup> must have same lang', () => {
  830. expect(() =>
  831. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  832. ).toThrow(`<script> and <script setup> must have the same language type`)
  833. })
  834. const moduleErrorMsg = `cannot contain ES module exports`
  835. test('non-type named exports', () => {
  836. expect(() =>
  837. compile(`<script setup>
  838. export const a = 1
  839. </script>`)
  840. ).toThrow(moduleErrorMsg)
  841. expect(() =>
  842. compile(`<script setup>
  843. export * from './foo'
  844. </script>`)
  845. ).toThrow(moduleErrorMsg)
  846. expect(() =>
  847. compile(`<script setup>
  848. const bar = 1
  849. export { bar as default }
  850. </script>`)
  851. ).toThrow(moduleErrorMsg)
  852. })
  853. test('defineProps/Emit() w/ both type and non-type args', () => {
  854. expect(() => {
  855. compile(`<script setup lang="ts">
  856. defineProps<{}>({})
  857. </script>`)
  858. }).toThrow(`cannot accept both type and non-type arguments`)
  859. expect(() => {
  860. compile(`<script setup lang="ts">
  861. defineEmits<{}>({})
  862. </script>`)
  863. }).toThrow(`cannot accept both type and non-type arguments`)
  864. })
  865. test('defineProps/Emit() referencing local var', () => {
  866. expect(() =>
  867. compile(`<script setup>
  868. const bar = 1
  869. defineProps({
  870. foo: {
  871. default: () => bar
  872. }
  873. })
  874. </script>`)
  875. ).toThrow(`cannot reference locally declared variables`)
  876. expect(() =>
  877. compile(`<script setup>
  878. const bar = 'hello'
  879. defineEmits([bar])
  880. </script>`)
  881. ).toThrow(`cannot reference locally declared variables`)
  882. })
  883. test('should allow defineProps/Emit() referencing scope var', () => {
  884. assertCode(
  885. compile(`<script setup>
  886. const bar = 1
  887. defineProps({
  888. foo: {
  889. default: bar => bar + 1
  890. }
  891. })
  892. defineEmits({
  893. foo: bar => bar > 1
  894. })
  895. </script>`).content
  896. )
  897. })
  898. test('should allow defineProps/Emit() referencing imported binding', () => {
  899. assertCode(
  900. compile(`<script setup>
  901. import { bar } from './bar'
  902. defineProps({
  903. foo: {
  904. default: () => bar
  905. }
  906. })
  907. defineEmits({
  908. foo: () => bar > 1
  909. })
  910. </script>`).content
  911. )
  912. })
  913. })
  914. })
  915. describe('SFC analyze <script> bindings', () => {
  916. it('can parse decorators syntax in typescript block', () => {
  917. const { scriptAst } = compile(`
  918. <script lang="ts">
  919. import { Options, Vue } from 'vue-class-component';
  920. @Options({
  921. components: {
  922. HelloWorld,
  923. },
  924. props: ['foo', 'bar']
  925. })
  926. export default class Home extends Vue {}
  927. </script>
  928. `)
  929. expect(scriptAst).toBeDefined()
  930. })
  931. it('recognizes props array declaration', () => {
  932. const { bindings } = compile(`
  933. <script>
  934. export default {
  935. props: ['foo', 'bar']
  936. }
  937. </script>
  938. `)
  939. expect(bindings).toStrictEqual({
  940. foo: BindingTypes.PROPS,
  941. bar: BindingTypes.PROPS
  942. })
  943. expect(bindings!.__isScriptSetup).toBe(false)
  944. })
  945. it('recognizes props object declaration', () => {
  946. const { bindings } = compile(`
  947. <script>
  948. export default {
  949. props: {
  950. foo: String,
  951. bar: {
  952. type: String,
  953. },
  954. baz: null,
  955. qux: [String, Number]
  956. }
  957. }
  958. </script>
  959. `)
  960. expect(bindings).toStrictEqual({
  961. foo: BindingTypes.PROPS,
  962. bar: BindingTypes.PROPS,
  963. baz: BindingTypes.PROPS,
  964. qux: BindingTypes.PROPS
  965. })
  966. expect(bindings!.__isScriptSetup).toBe(false)
  967. })
  968. it('recognizes setup return', () => {
  969. const { bindings } = compile(`
  970. <script>
  971. const bar = 2
  972. export default {
  973. setup() {
  974. return {
  975. foo: 1,
  976. bar
  977. }
  978. }
  979. }
  980. </script>
  981. `)
  982. expect(bindings).toStrictEqual({
  983. foo: BindingTypes.SETUP_MAYBE_REF,
  984. bar: BindingTypes.SETUP_MAYBE_REF
  985. })
  986. expect(bindings!.__isScriptSetup).toBe(false)
  987. })
  988. it('recognizes async setup return', () => {
  989. const { bindings } = compile(`
  990. <script>
  991. const bar = 2
  992. export default {
  993. async setup() {
  994. return {
  995. foo: 1,
  996. bar
  997. }
  998. }
  999. }
  1000. </script>
  1001. `)
  1002. expect(bindings).toStrictEqual({
  1003. foo: BindingTypes.SETUP_MAYBE_REF,
  1004. bar: BindingTypes.SETUP_MAYBE_REF
  1005. })
  1006. expect(bindings!.__isScriptSetup).toBe(false)
  1007. })
  1008. it('recognizes data return', () => {
  1009. const { bindings } = compile(`
  1010. <script>
  1011. const bar = 2
  1012. export default {
  1013. data() {
  1014. return {
  1015. foo: null,
  1016. bar
  1017. }
  1018. }
  1019. }
  1020. </script>
  1021. `)
  1022. expect(bindings).toStrictEqual({
  1023. foo: BindingTypes.DATA,
  1024. bar: BindingTypes.DATA
  1025. })
  1026. })
  1027. it('recognizes methods', () => {
  1028. const { bindings } = compile(`
  1029. <script>
  1030. export default {
  1031. methods: {
  1032. foo() {}
  1033. }
  1034. }
  1035. </script>
  1036. `)
  1037. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1038. })
  1039. it('recognizes computeds', () => {
  1040. const { bindings } = compile(`
  1041. <script>
  1042. export default {
  1043. computed: {
  1044. foo() {},
  1045. bar: {
  1046. get() {},
  1047. set() {},
  1048. }
  1049. }
  1050. }
  1051. </script>
  1052. `)
  1053. expect(bindings).toStrictEqual({
  1054. foo: BindingTypes.OPTIONS,
  1055. bar: BindingTypes.OPTIONS
  1056. })
  1057. })
  1058. it('recognizes injections array declaration', () => {
  1059. const { bindings } = compile(`
  1060. <script>
  1061. export default {
  1062. inject: ['foo', 'bar']
  1063. }
  1064. </script>
  1065. `)
  1066. expect(bindings).toStrictEqual({
  1067. foo: BindingTypes.OPTIONS,
  1068. bar: BindingTypes.OPTIONS
  1069. })
  1070. })
  1071. it('recognizes injections object declaration', () => {
  1072. const { bindings } = compile(`
  1073. <script>
  1074. export default {
  1075. inject: {
  1076. foo: {},
  1077. bar: {},
  1078. }
  1079. }
  1080. </script>
  1081. `)
  1082. expect(bindings).toStrictEqual({
  1083. foo: BindingTypes.OPTIONS,
  1084. bar: BindingTypes.OPTIONS
  1085. })
  1086. })
  1087. it('works for mixed bindings', () => {
  1088. const { bindings } = compile(`
  1089. <script>
  1090. export default {
  1091. inject: ['foo'],
  1092. props: {
  1093. bar: String,
  1094. },
  1095. setup() {
  1096. return {
  1097. baz: null,
  1098. }
  1099. },
  1100. data() {
  1101. return {
  1102. qux: null
  1103. }
  1104. },
  1105. methods: {
  1106. quux() {}
  1107. },
  1108. computed: {
  1109. quuz() {}
  1110. }
  1111. }
  1112. </script>
  1113. `)
  1114. expect(bindings).toStrictEqual({
  1115. foo: BindingTypes.OPTIONS,
  1116. bar: BindingTypes.PROPS,
  1117. baz: BindingTypes.SETUP_MAYBE_REF,
  1118. qux: BindingTypes.DATA,
  1119. quux: BindingTypes.OPTIONS,
  1120. quuz: BindingTypes.OPTIONS
  1121. })
  1122. })
  1123. it('works for script setup', () => {
  1124. const { bindings } = compile(`
  1125. <script setup>
  1126. import { ref as r } from 'vue'
  1127. defineProps({
  1128. foo: String
  1129. })
  1130. const a = r(1)
  1131. let b = 2
  1132. const c = 3
  1133. const { d } = someFoo()
  1134. let { e } = someBar()
  1135. </script>
  1136. `)
  1137. expect(bindings).toStrictEqual({
  1138. r: BindingTypes.SETUP_CONST,
  1139. a: BindingTypes.SETUP_REF,
  1140. b: BindingTypes.SETUP_LET,
  1141. c: BindingTypes.SETUP_CONST,
  1142. d: BindingTypes.SETUP_MAYBE_REF,
  1143. e: BindingTypes.SETUP_LET,
  1144. foo: BindingTypes.PROPS
  1145. })
  1146. })
  1147. })