compileScript.spec.ts 35 KB

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