compileScript.spec.ts 35 KB

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