compileScript.spec.ts 39 KB

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