compileScript.spec.ts 37 KB

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