compileScript.spec.ts 37 KB

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