compileScript.spec.ts 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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. test('const Enum', () => {
  752. const { content, bindings } = compile(
  753. `<script setup lang="ts">
  754. const enum Foo { A = 123 }
  755. </script>`
  756. )
  757. assertCode(content)
  758. expect(bindings).toStrictEqual({
  759. Foo: BindingTypes.SETUP_CONST
  760. })
  761. })
  762. })
  763. describe('async/await detection', () => {
  764. function assertAwaitDetection(
  765. code: string,
  766. expected: string | ((content: string) => boolean),
  767. shouldAsync = true
  768. ) {
  769. const { content } = compile(`<script setup>${code}</script>`, {
  770. refSugar: true
  771. })
  772. if (shouldAsync) {
  773. expect(content).toMatch(`let __temp, __restore`)
  774. }
  775. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  776. if (typeof expected === 'string') {
  777. expect(content).toMatch(expected)
  778. } else {
  779. expect(expected(content)).toBe(true)
  780. }
  781. }
  782. test('expression statement', () => {
  783. assertAwaitDetection(
  784. `await foo`,
  785. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  786. )
  787. })
  788. test('variable', () => {
  789. assertAwaitDetection(
  790. `const a = 1 + (await foo)`,
  791. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  792. )
  793. })
  794. test('ref', () => {
  795. assertAwaitDetection(
  796. `let a = $ref(1 + (await foo))`,
  797. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  798. )
  799. })
  800. test('nested statements', () => {
  801. assertAwaitDetection(`if (ok) { await foo } else { await bar }`, code => {
  802. return (
  803. code.includes(
  804. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  805. ) &&
  806. code.includes(
  807. `;(([__temp,__restore]=_withAsyncContext(()=>(bar))),__temp=await __temp,__restore())`
  808. )
  809. )
  810. })
  811. })
  812. test('should ignore await inside functions', () => {
  813. // function declaration
  814. assertAwaitDetection(
  815. `async function foo() { await bar }`,
  816. `await bar`,
  817. false
  818. )
  819. // function expression
  820. assertAwaitDetection(
  821. `const foo = async () => { await bar }`,
  822. `await bar`,
  823. false
  824. )
  825. // object method
  826. assertAwaitDetection(
  827. `const obj = { async method() { await bar }}`,
  828. `await bar`,
  829. false
  830. )
  831. // class method
  832. assertAwaitDetection(
  833. `const cls = class Foo { async method() { await bar }}`,
  834. `await bar`,
  835. false
  836. )
  837. })
  838. })
  839. describe('errors', () => {
  840. test('<script> and <script setup> must have same lang', () => {
  841. expect(() =>
  842. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  843. ).toThrow(`<script> and <script setup> must have the same language type`)
  844. })
  845. const moduleErrorMsg = `cannot contain ES module exports`
  846. test('non-type named exports', () => {
  847. expect(() =>
  848. compile(`<script setup>
  849. export const a = 1
  850. </script>`)
  851. ).toThrow(moduleErrorMsg)
  852. expect(() =>
  853. compile(`<script setup>
  854. export * from './foo'
  855. </script>`)
  856. ).toThrow(moduleErrorMsg)
  857. expect(() =>
  858. compile(`<script setup>
  859. const bar = 1
  860. export { bar as default }
  861. </script>`)
  862. ).toThrow(moduleErrorMsg)
  863. })
  864. test('defineProps/Emit() w/ both type and non-type args', () => {
  865. expect(() => {
  866. compile(`<script setup lang="ts">
  867. defineProps<{}>({})
  868. </script>`)
  869. }).toThrow(`cannot accept both type and non-type arguments`)
  870. expect(() => {
  871. compile(`<script setup lang="ts">
  872. defineEmits<{}>({})
  873. </script>`)
  874. }).toThrow(`cannot accept both type and non-type arguments`)
  875. })
  876. test('defineProps/Emit() referencing local var', () => {
  877. expect(() =>
  878. compile(`<script setup>
  879. const bar = 1
  880. defineProps({
  881. foo: {
  882. default: () => bar
  883. }
  884. })
  885. </script>`)
  886. ).toThrow(`cannot reference locally declared variables`)
  887. expect(() =>
  888. compile(`<script setup>
  889. const bar = 'hello'
  890. defineEmits([bar])
  891. </script>`)
  892. ).toThrow(`cannot reference locally declared variables`)
  893. })
  894. test('should allow defineProps/Emit() referencing scope var', () => {
  895. assertCode(
  896. compile(`<script setup>
  897. const bar = 1
  898. defineProps({
  899. foo: {
  900. default: bar => bar + 1
  901. }
  902. })
  903. defineEmits({
  904. foo: bar => bar > 1
  905. })
  906. </script>`).content
  907. )
  908. })
  909. test('should allow defineProps/Emit() referencing imported binding', () => {
  910. assertCode(
  911. compile(`<script setup>
  912. import { bar } from './bar'
  913. defineProps({
  914. foo: {
  915. default: () => bar
  916. }
  917. })
  918. defineEmits({
  919. foo: () => bar > 1
  920. })
  921. </script>`).content
  922. )
  923. })
  924. })
  925. })
  926. describe('SFC analyze <script> bindings', () => {
  927. it('can parse decorators syntax in typescript block', () => {
  928. const { scriptAst } = compile(`
  929. <script lang="ts">
  930. import { Options, Vue } from 'vue-class-component';
  931. @Options({
  932. components: {
  933. HelloWorld,
  934. },
  935. props: ['foo', 'bar']
  936. })
  937. export default class Home extends Vue {}
  938. </script>
  939. `)
  940. expect(scriptAst).toBeDefined()
  941. })
  942. it('recognizes props array declaration', () => {
  943. const { bindings } = compile(`
  944. <script>
  945. export default {
  946. props: ['foo', 'bar']
  947. }
  948. </script>
  949. `)
  950. expect(bindings).toStrictEqual({
  951. foo: BindingTypes.PROPS,
  952. bar: BindingTypes.PROPS
  953. })
  954. expect(bindings!.__isScriptSetup).toBe(false)
  955. })
  956. it('recognizes props object declaration', () => {
  957. const { bindings } = compile(`
  958. <script>
  959. export default {
  960. props: {
  961. foo: String,
  962. bar: {
  963. type: String,
  964. },
  965. baz: null,
  966. qux: [String, Number]
  967. }
  968. }
  969. </script>
  970. `)
  971. expect(bindings).toStrictEqual({
  972. foo: BindingTypes.PROPS,
  973. bar: BindingTypes.PROPS,
  974. baz: BindingTypes.PROPS,
  975. qux: BindingTypes.PROPS
  976. })
  977. expect(bindings!.__isScriptSetup).toBe(false)
  978. })
  979. it('recognizes setup return', () => {
  980. const { bindings } = compile(`
  981. <script>
  982. const bar = 2
  983. export default {
  984. setup() {
  985. return {
  986. foo: 1,
  987. bar
  988. }
  989. }
  990. }
  991. </script>
  992. `)
  993. expect(bindings).toStrictEqual({
  994. foo: BindingTypes.SETUP_MAYBE_REF,
  995. bar: BindingTypes.SETUP_MAYBE_REF
  996. })
  997. expect(bindings!.__isScriptSetup).toBe(false)
  998. })
  999. it('recognizes async setup return', () => {
  1000. const { bindings } = compile(`
  1001. <script>
  1002. const bar = 2
  1003. export default {
  1004. async setup() {
  1005. return {
  1006. foo: 1,
  1007. bar
  1008. }
  1009. }
  1010. }
  1011. </script>
  1012. `)
  1013. expect(bindings).toStrictEqual({
  1014. foo: BindingTypes.SETUP_MAYBE_REF,
  1015. bar: BindingTypes.SETUP_MAYBE_REF
  1016. })
  1017. expect(bindings!.__isScriptSetup).toBe(false)
  1018. })
  1019. it('recognizes data return', () => {
  1020. const { bindings } = compile(`
  1021. <script>
  1022. const bar = 2
  1023. export default {
  1024. data() {
  1025. return {
  1026. foo: null,
  1027. bar
  1028. }
  1029. }
  1030. }
  1031. </script>
  1032. `)
  1033. expect(bindings).toStrictEqual({
  1034. foo: BindingTypes.DATA,
  1035. bar: BindingTypes.DATA
  1036. })
  1037. })
  1038. it('recognizes methods', () => {
  1039. const { bindings } = compile(`
  1040. <script>
  1041. export default {
  1042. methods: {
  1043. foo() {}
  1044. }
  1045. }
  1046. </script>
  1047. `)
  1048. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1049. })
  1050. it('recognizes computeds', () => {
  1051. const { bindings } = compile(`
  1052. <script>
  1053. export default {
  1054. computed: {
  1055. foo() {},
  1056. bar: {
  1057. get() {},
  1058. set() {},
  1059. }
  1060. }
  1061. }
  1062. </script>
  1063. `)
  1064. expect(bindings).toStrictEqual({
  1065. foo: BindingTypes.OPTIONS,
  1066. bar: BindingTypes.OPTIONS
  1067. })
  1068. })
  1069. it('recognizes injections array declaration', () => {
  1070. const { bindings } = compile(`
  1071. <script>
  1072. export default {
  1073. inject: ['foo', 'bar']
  1074. }
  1075. </script>
  1076. `)
  1077. expect(bindings).toStrictEqual({
  1078. foo: BindingTypes.OPTIONS,
  1079. bar: BindingTypes.OPTIONS
  1080. })
  1081. })
  1082. it('recognizes injections object declaration', () => {
  1083. const { bindings } = compile(`
  1084. <script>
  1085. export default {
  1086. inject: {
  1087. foo: {},
  1088. bar: {},
  1089. }
  1090. }
  1091. </script>
  1092. `)
  1093. expect(bindings).toStrictEqual({
  1094. foo: BindingTypes.OPTIONS,
  1095. bar: BindingTypes.OPTIONS
  1096. })
  1097. })
  1098. it('works for mixed bindings', () => {
  1099. const { bindings } = compile(`
  1100. <script>
  1101. export default {
  1102. inject: ['foo'],
  1103. props: {
  1104. bar: String,
  1105. },
  1106. setup() {
  1107. return {
  1108. baz: null,
  1109. }
  1110. },
  1111. data() {
  1112. return {
  1113. qux: null
  1114. }
  1115. },
  1116. methods: {
  1117. quux() {}
  1118. },
  1119. computed: {
  1120. quuz() {}
  1121. }
  1122. }
  1123. </script>
  1124. `)
  1125. expect(bindings).toStrictEqual({
  1126. foo: BindingTypes.OPTIONS,
  1127. bar: BindingTypes.PROPS,
  1128. baz: BindingTypes.SETUP_MAYBE_REF,
  1129. qux: BindingTypes.DATA,
  1130. quux: BindingTypes.OPTIONS,
  1131. quuz: BindingTypes.OPTIONS
  1132. })
  1133. })
  1134. it('works for script setup', () => {
  1135. const { bindings } = compile(`
  1136. <script setup>
  1137. import { ref as r } from 'vue'
  1138. defineProps({
  1139. foo: String
  1140. })
  1141. const a = r(1)
  1142. let b = 2
  1143. const c = 3
  1144. const { d } = someFoo()
  1145. let { e } = someBar()
  1146. </script>
  1147. `)
  1148. expect(bindings).toStrictEqual({
  1149. r: BindingTypes.SETUP_CONST,
  1150. a: BindingTypes.SETUP_REF,
  1151. b: BindingTypes.SETUP_LET,
  1152. c: BindingTypes.SETUP_CONST,
  1153. d: BindingTypes.SETUP_MAYBE_REF,
  1154. e: BindingTypes.SETUP_LET,
  1155. foo: BindingTypes.PROPS
  1156. })
  1157. })
  1158. })