compileScript.spec.ts 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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. }>()
  488. </script>`)
  489. assertCode(content)
  490. expect(content).toMatch(`string: { type: String, required: true }`)
  491. expect(content).toMatch(`number: { type: Number, required: true }`)
  492. expect(content).toMatch(`boolean: { type: Boolean, required: true }`)
  493. expect(content).toMatch(`object: { type: Object, required: true }`)
  494. expect(content).toMatch(`objectLiteral: { type: Object, required: true }`)
  495. expect(content).toMatch(`fn: { type: Function, required: true }`)
  496. expect(content).toMatch(`functionRef: { type: Function, required: true }`)
  497. expect(content).toMatch(`objectRef: { type: Object, required: true }`)
  498. expect(content).toMatch(`array: { type: Array, required: true }`)
  499. expect(content).toMatch(`arrayRef: { type: Array, required: true }`)
  500. expect(content).toMatch(`tuple: { type: Array, required: true }`)
  501. expect(content).toMatch(`set: { type: Set, required: true }`)
  502. expect(content).toMatch(`literal: { type: String, required: true }`)
  503. expect(content).toMatch(`optional: { type: null, required: false }`)
  504. expect(content).toMatch(`recordRef: { type: Object, required: true }`)
  505. expect(content).toMatch(`interface: { type: Object, required: true }`)
  506. expect(content).toMatch(`alias: { type: Array, required: true }`)
  507. expect(content).toMatch(`method: { type: Function, required: true }`)
  508. expect(content).toMatch(
  509. `union: { type: [String, Number], required: true }`
  510. )
  511. expect(content).toMatch(
  512. `literalUnion: { type: [String, String], required: true }`
  513. )
  514. expect(content).toMatch(
  515. `literalUnionMixed: { type: [String, Number, Boolean], required: true }`
  516. )
  517. expect(content).toMatch(`intersection: { type: Object, required: true }`)
  518. expect(bindings).toStrictEqual({
  519. string: BindingTypes.PROPS,
  520. number: BindingTypes.PROPS,
  521. boolean: BindingTypes.PROPS,
  522. object: BindingTypes.PROPS,
  523. objectLiteral: BindingTypes.PROPS,
  524. fn: BindingTypes.PROPS,
  525. functionRef: BindingTypes.PROPS,
  526. objectRef: BindingTypes.PROPS,
  527. array: BindingTypes.PROPS,
  528. arrayRef: BindingTypes.PROPS,
  529. tuple: BindingTypes.PROPS,
  530. set: BindingTypes.PROPS,
  531. literal: BindingTypes.PROPS,
  532. optional: BindingTypes.PROPS,
  533. recordRef: BindingTypes.PROPS,
  534. interface: BindingTypes.PROPS,
  535. alias: BindingTypes.PROPS,
  536. method: BindingTypes.PROPS,
  537. union: BindingTypes.PROPS,
  538. literalUnion: BindingTypes.PROPS,
  539. literalUnionMixed: BindingTypes.PROPS,
  540. intersection: BindingTypes.PROPS
  541. })
  542. })
  543. test('defineProps w/ interface', () => {
  544. const { content, bindings } = compile(`
  545. <script setup lang="ts">
  546. interface Props { x?: number }
  547. defineProps<Props>()
  548. </script>
  549. `)
  550. assertCode(content)
  551. expect(content).toMatch(`x: { type: Number, required: false }`)
  552. expect(bindings).toStrictEqual({
  553. x: BindingTypes.PROPS
  554. })
  555. })
  556. test('defineProps w/ exported interface', () => {
  557. const { content, bindings } = compile(`
  558. <script setup lang="ts">
  559. export interface Props { x?: number }
  560. defineProps<Props>()
  561. </script>
  562. `)
  563. assertCode(content)
  564. expect(content).toMatch(`x: { type: Number, required: false }`)
  565. expect(bindings).toStrictEqual({
  566. x: BindingTypes.PROPS
  567. })
  568. })
  569. test('defineProps w/ type alias', () => {
  570. const { content, bindings } = compile(`
  571. <script setup lang="ts">
  572. type Props = { x?: number }
  573. defineProps<Props>()
  574. </script>
  575. `)
  576. assertCode(content)
  577. expect(content).toMatch(`x: { type: Number, required: false }`)
  578. expect(bindings).toStrictEqual({
  579. x: BindingTypes.PROPS
  580. })
  581. })
  582. test('defineProps w/ exported type alias', () => {
  583. const { content, bindings } = compile(`
  584. <script setup lang="ts">
  585. export type Props = { x?: number }
  586. defineProps<Props>()
  587. </script>
  588. `)
  589. assertCode(content)
  590. expect(content).toMatch(`x: { type: Number, required: false }`)
  591. expect(bindings).toStrictEqual({
  592. x: BindingTypes.PROPS
  593. })
  594. })
  595. test('withDefaults (static)', () => {
  596. const { content, bindings } = compile(`
  597. <script setup lang="ts">
  598. const props = withDefaults(defineProps<{
  599. foo?: string
  600. bar?: number
  601. }>(), {
  602. foo: 'hi'
  603. })
  604. </script>
  605. `)
  606. assertCode(content)
  607. expect(content).toMatch(
  608. `foo: { type: String, required: false, default: 'hi' }`
  609. )
  610. expect(content).toMatch(`bar: { type: Number, required: false }`)
  611. expect(content).toMatch(`const props = __props`)
  612. expect(bindings).toStrictEqual({
  613. foo: BindingTypes.PROPS,
  614. bar: BindingTypes.PROPS,
  615. props: BindingTypes.SETUP_CONST
  616. })
  617. })
  618. test('withDefaults (dynamic)', () => {
  619. const { content } = compile(`
  620. <script setup lang="ts">
  621. import { defaults } from './foo'
  622. const props = withDefaults(defineProps<{
  623. foo?: string
  624. bar?: number
  625. }>(), { ...defaults })
  626. </script>
  627. `)
  628. assertCode(content)
  629. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  630. expect(content).toMatch(
  631. `
  632. _mergeDefaults({
  633. foo: { type: String, required: false },
  634. bar: { type: Number, required: false }
  635. }, { ...defaults })`.trim()
  636. )
  637. })
  638. test('defineEmits w/ type', () => {
  639. const { content } = compile(`
  640. <script setup lang="ts">
  641. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  642. </script>
  643. `)
  644. assertCode(content)
  645. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  646. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  647. })
  648. test('defineEmits w/ type (union)', () => {
  649. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  650. expect(() =>
  651. compile(`
  652. <script setup lang="ts">
  653. const emit = defineEmits<${type}>()
  654. </script>
  655. `)
  656. ).toThrow()
  657. })
  658. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  659. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  660. const { content } = compile(`
  661. <script setup lang="ts">
  662. const emit = defineEmits<${type}>()
  663. </script>
  664. `)
  665. assertCode(content)
  666. expect(content).toMatch(`emit: (${type}),`)
  667. expect(content).toMatch(
  668. `emits: ["foo", "bar", "baz"] as unknown as undefined`
  669. )
  670. })
  671. test('defineEmits w/ type (interface)', () => {
  672. const { content } = compile(`
  673. <script setup lang="ts">
  674. interface Emits { (e: 'foo' | 'bar'): void }
  675. const emit = defineEmits<Emits>()
  676. </script>
  677. `)
  678. assertCode(content)
  679. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  680. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  681. })
  682. test('defineEmits w/ type (exported interface)', () => {
  683. const { content } = compile(`
  684. <script setup lang="ts">
  685. export interface Emits { (e: 'foo' | 'bar'): void }
  686. const emit = defineEmits<Emits>()
  687. </script>
  688. `)
  689. assertCode(content)
  690. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  691. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  692. })
  693. test('defineEmits w/ type (type alias)', () => {
  694. const { content } = compile(`
  695. <script setup lang="ts">
  696. type Emits = { (e: 'foo' | 'bar'): void }
  697. const emit = defineEmits<Emits>()
  698. </script>
  699. `)
  700. assertCode(content)
  701. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  702. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  703. })
  704. test('defineEmits w/ type (exported type alias)', () => {
  705. const { content } = compile(`
  706. <script setup lang="ts">
  707. export type Emits = { (e: 'foo' | 'bar'): void }
  708. const emit = defineEmits<Emits>()
  709. </script>
  710. `)
  711. assertCode(content)
  712. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  713. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  714. })
  715. test('defineEmits w/ type (referenced function type)', () => {
  716. const { content } = compile(`
  717. <script setup lang="ts">
  718. type Emits = (e: 'foo' | 'bar') => void
  719. const emit = defineEmits<Emits>()
  720. </script>
  721. `)
  722. assertCode(content)
  723. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  724. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  725. })
  726. test('defineEmits w/ type (referenced exported function type)', () => {
  727. const { content } = compile(`
  728. <script setup lang="ts">
  729. export type Emits = (e: 'foo' | 'bar') => void
  730. const emit = defineEmits<Emits>()
  731. </script>
  732. `)
  733. assertCode(content)
  734. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  735. expect(content).toMatch(`emits: ["foo", "bar"] as unknown as undefined`)
  736. })
  737. test('runtime Enum', () => {
  738. const { content, bindings } = compile(
  739. `<script setup lang="ts">
  740. enum Foo { A = 123 }
  741. </script>`
  742. )
  743. assertCode(content)
  744. expect(bindings).toStrictEqual({
  745. Foo: BindingTypes.SETUP_CONST
  746. })
  747. })
  748. })
  749. describe('async/await detection', () => {
  750. function assertAwaitDetection(
  751. code: string,
  752. expected: string | ((content: string) => boolean),
  753. shouldAsync = true
  754. ) {
  755. const { content } = compile(`<script setup>${code}</script>`, {
  756. refSugar: true
  757. })
  758. if (shouldAsync) {
  759. expect(content).toMatch(`let __temp, __restore`)
  760. }
  761. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  762. if (typeof expected === 'string') {
  763. expect(content).toMatch(expected)
  764. } else {
  765. expect(expected(content)).toBe(true)
  766. }
  767. }
  768. test('expression statement', () => {
  769. assertAwaitDetection(
  770. `await foo`,
  771. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  772. )
  773. })
  774. test('variable', () => {
  775. assertAwaitDetection(
  776. `const a = 1 + (await foo)`,
  777. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  778. )
  779. })
  780. test('ref', () => {
  781. assertAwaitDetection(
  782. `let a = $ref(1 + (await foo))`,
  783. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  784. )
  785. })
  786. test('nested statements', () => {
  787. assertAwaitDetection(`if (ok) { await foo } else { await bar }`, code => {
  788. return (
  789. code.includes(
  790. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  791. ) &&
  792. code.includes(
  793. `;(([__temp,__restore]=_withAsyncContext(()=>(bar))),__temp=await __temp,__restore())`
  794. )
  795. )
  796. })
  797. })
  798. test('should ignore await inside functions', () => {
  799. // function declaration
  800. assertAwaitDetection(
  801. `async function foo() { await bar }`,
  802. `await bar`,
  803. false
  804. )
  805. // function expression
  806. assertAwaitDetection(
  807. `const foo = async () => { await bar }`,
  808. `await bar`,
  809. false
  810. )
  811. // object method
  812. assertAwaitDetection(
  813. `const obj = { async method() { await bar }}`,
  814. `await bar`,
  815. false
  816. )
  817. // class method
  818. assertAwaitDetection(
  819. `const cls = class Foo { async method() { await bar }}`,
  820. `await bar`,
  821. false
  822. )
  823. })
  824. })
  825. describe('errors', () => {
  826. test('<script> and <script setup> must have same lang', () => {
  827. expect(() =>
  828. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  829. ).toThrow(`<script> and <script setup> must have the same language type`)
  830. })
  831. const moduleErrorMsg = `cannot contain ES module exports`
  832. test('non-type named exports', () => {
  833. expect(() =>
  834. compile(`<script setup>
  835. export const a = 1
  836. </script>`)
  837. ).toThrow(moduleErrorMsg)
  838. expect(() =>
  839. compile(`<script setup>
  840. export * from './foo'
  841. </script>`)
  842. ).toThrow(moduleErrorMsg)
  843. expect(() =>
  844. compile(`<script setup>
  845. const bar = 1
  846. export { bar as default }
  847. </script>`)
  848. ).toThrow(moduleErrorMsg)
  849. })
  850. test('defineProps/Emit() w/ both type and non-type args', () => {
  851. expect(() => {
  852. compile(`<script setup lang="ts">
  853. defineProps<{}>({})
  854. </script>`)
  855. }).toThrow(`cannot accept both type and non-type arguments`)
  856. expect(() => {
  857. compile(`<script setup lang="ts">
  858. defineEmits<{}>({})
  859. </script>`)
  860. }).toThrow(`cannot accept both type and non-type arguments`)
  861. })
  862. test('defineProps/Emit() referencing local var', () => {
  863. expect(() =>
  864. compile(`<script setup>
  865. const bar = 1
  866. defineProps({
  867. foo: {
  868. default: () => bar
  869. }
  870. })
  871. </script>`)
  872. ).toThrow(`cannot reference locally declared variables`)
  873. expect(() =>
  874. compile(`<script setup>
  875. const bar = 'hello'
  876. defineEmits([bar])
  877. </script>`)
  878. ).toThrow(`cannot reference locally declared variables`)
  879. })
  880. test('should allow defineProps/Emit() referencing scope var', () => {
  881. assertCode(
  882. compile(`<script setup>
  883. const bar = 1
  884. defineProps({
  885. foo: {
  886. default: bar => bar + 1
  887. }
  888. })
  889. defineEmits({
  890. foo: bar => bar > 1
  891. })
  892. </script>`).content
  893. )
  894. })
  895. test('should allow defineProps/Emit() referencing imported binding', () => {
  896. assertCode(
  897. compile(`<script setup>
  898. import { bar } from './bar'
  899. defineProps({
  900. foo: {
  901. default: () => bar
  902. }
  903. })
  904. defineEmits({
  905. foo: () => bar > 1
  906. })
  907. </script>`).content
  908. )
  909. })
  910. })
  911. })
  912. describe('SFC analyze <script> bindings', () => {
  913. it('can parse decorators syntax in typescript block', () => {
  914. const { scriptAst } = compile(`
  915. <script lang="ts">
  916. import { Options, Vue } from 'vue-class-component';
  917. @Options({
  918. components: {
  919. HelloWorld,
  920. },
  921. props: ['foo', 'bar']
  922. })
  923. export default class Home extends Vue {}
  924. </script>
  925. `)
  926. expect(scriptAst).toBeDefined()
  927. })
  928. it('recognizes props array declaration', () => {
  929. const { bindings } = compile(`
  930. <script>
  931. export default {
  932. props: ['foo', 'bar']
  933. }
  934. </script>
  935. `)
  936. expect(bindings).toStrictEqual({
  937. foo: BindingTypes.PROPS,
  938. bar: BindingTypes.PROPS
  939. })
  940. expect(bindings!.__isScriptSetup).toBe(false)
  941. })
  942. it('recognizes props object declaration', () => {
  943. const { bindings } = compile(`
  944. <script>
  945. export default {
  946. props: {
  947. foo: String,
  948. bar: {
  949. type: String,
  950. },
  951. baz: null,
  952. qux: [String, Number]
  953. }
  954. }
  955. </script>
  956. `)
  957. expect(bindings).toStrictEqual({
  958. foo: BindingTypes.PROPS,
  959. bar: BindingTypes.PROPS,
  960. baz: BindingTypes.PROPS,
  961. qux: BindingTypes.PROPS
  962. })
  963. expect(bindings!.__isScriptSetup).toBe(false)
  964. })
  965. it('recognizes setup return', () => {
  966. const { bindings } = compile(`
  967. <script>
  968. const bar = 2
  969. export default {
  970. setup() {
  971. return {
  972. foo: 1,
  973. bar
  974. }
  975. }
  976. }
  977. </script>
  978. `)
  979. expect(bindings).toStrictEqual({
  980. foo: BindingTypes.SETUP_MAYBE_REF,
  981. bar: BindingTypes.SETUP_MAYBE_REF
  982. })
  983. expect(bindings!.__isScriptSetup).toBe(false)
  984. })
  985. it('recognizes async setup return', () => {
  986. const { bindings } = compile(`
  987. <script>
  988. const bar = 2
  989. export default {
  990. async setup() {
  991. return {
  992. foo: 1,
  993. bar
  994. }
  995. }
  996. }
  997. </script>
  998. `)
  999. expect(bindings).toStrictEqual({
  1000. foo: BindingTypes.SETUP_MAYBE_REF,
  1001. bar: BindingTypes.SETUP_MAYBE_REF
  1002. })
  1003. expect(bindings!.__isScriptSetup).toBe(false)
  1004. })
  1005. it('recognizes data return', () => {
  1006. const { bindings } = compile(`
  1007. <script>
  1008. const bar = 2
  1009. export default {
  1010. data() {
  1011. return {
  1012. foo: null,
  1013. bar
  1014. }
  1015. }
  1016. }
  1017. </script>
  1018. `)
  1019. expect(bindings).toStrictEqual({
  1020. foo: BindingTypes.DATA,
  1021. bar: BindingTypes.DATA
  1022. })
  1023. })
  1024. it('recognizes methods', () => {
  1025. const { bindings } = compile(`
  1026. <script>
  1027. export default {
  1028. methods: {
  1029. foo() {}
  1030. }
  1031. }
  1032. </script>
  1033. `)
  1034. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1035. })
  1036. it('recognizes computeds', () => {
  1037. const { bindings } = compile(`
  1038. <script>
  1039. export default {
  1040. computed: {
  1041. foo() {},
  1042. bar: {
  1043. get() {},
  1044. set() {},
  1045. }
  1046. }
  1047. }
  1048. </script>
  1049. `)
  1050. expect(bindings).toStrictEqual({
  1051. foo: BindingTypes.OPTIONS,
  1052. bar: BindingTypes.OPTIONS
  1053. })
  1054. })
  1055. it('recognizes injections array declaration', () => {
  1056. const { bindings } = compile(`
  1057. <script>
  1058. export default {
  1059. inject: ['foo', 'bar']
  1060. }
  1061. </script>
  1062. `)
  1063. expect(bindings).toStrictEqual({
  1064. foo: BindingTypes.OPTIONS,
  1065. bar: BindingTypes.OPTIONS
  1066. })
  1067. })
  1068. it('recognizes injections object declaration', () => {
  1069. const { bindings } = compile(`
  1070. <script>
  1071. export default {
  1072. inject: {
  1073. foo: {},
  1074. bar: {},
  1075. }
  1076. }
  1077. </script>
  1078. `)
  1079. expect(bindings).toStrictEqual({
  1080. foo: BindingTypes.OPTIONS,
  1081. bar: BindingTypes.OPTIONS
  1082. })
  1083. })
  1084. it('works for mixed bindings', () => {
  1085. const { bindings } = compile(`
  1086. <script>
  1087. export default {
  1088. inject: ['foo'],
  1089. props: {
  1090. bar: String,
  1091. },
  1092. setup() {
  1093. return {
  1094. baz: null,
  1095. }
  1096. },
  1097. data() {
  1098. return {
  1099. qux: null
  1100. }
  1101. },
  1102. methods: {
  1103. quux() {}
  1104. },
  1105. computed: {
  1106. quuz() {}
  1107. }
  1108. }
  1109. </script>
  1110. `)
  1111. expect(bindings).toStrictEqual({
  1112. foo: BindingTypes.OPTIONS,
  1113. bar: BindingTypes.PROPS,
  1114. baz: BindingTypes.SETUP_MAYBE_REF,
  1115. qux: BindingTypes.DATA,
  1116. quux: BindingTypes.OPTIONS,
  1117. quuz: BindingTypes.OPTIONS
  1118. })
  1119. })
  1120. it('works for script setup', () => {
  1121. const { bindings } = compile(`
  1122. <script setup>
  1123. import { ref as r } from 'vue'
  1124. defineProps({
  1125. foo: String
  1126. })
  1127. const a = r(1)
  1128. let b = 2
  1129. const c = 3
  1130. const { d } = someFoo()
  1131. let { e } = someBar()
  1132. </script>
  1133. `)
  1134. expect(bindings).toStrictEqual({
  1135. r: BindingTypes.SETUP_CONST,
  1136. a: BindingTypes.SETUP_REF,
  1137. b: BindingTypes.SETUP_LET,
  1138. c: BindingTypes.SETUP_CONST,
  1139. d: BindingTypes.SETUP_MAYBE_REF,
  1140. e: BindingTypes.SETUP_LET,
  1141. foo: BindingTypes.PROPS
  1142. })
  1143. })
  1144. })