compileScript.spec.ts 35 KB

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