compileScript.spec.ts 35 KB

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