compileScript.spec.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  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"]`)
  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(`emits: ["foo", "bar", "baz"]`)
  840. })
  841. test('defineEmits w/ type (interface)', () => {
  842. const { content } = compile(`
  843. <script setup lang="ts">
  844. interface Emits { (e: 'foo' | 'bar'): void }
  845. const emit = defineEmits<Emits>()
  846. </script>
  847. `)
  848. assertCode(content)
  849. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  850. expect(content).toMatch(`emits: ["foo", "bar"]`)
  851. })
  852. test('defineEmits w/ type (exported interface)', () => {
  853. const { content } = compile(`
  854. <script setup lang="ts">
  855. export interface Emits { (e: 'foo' | 'bar'): void }
  856. const emit = defineEmits<Emits>()
  857. </script>
  858. `)
  859. assertCode(content)
  860. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  861. expect(content).toMatch(`emits: ["foo", "bar"]`)
  862. })
  863. test('defineEmits w/ type (type alias)', () => {
  864. const { content } = compile(`
  865. <script setup lang="ts">
  866. type Emits = { (e: 'foo' | 'bar'): void }
  867. const emit = defineEmits<Emits>()
  868. </script>
  869. `)
  870. assertCode(content)
  871. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  872. expect(content).toMatch(`emits: ["foo", "bar"]`)
  873. })
  874. test('defineEmits w/ type (exported type alias)', () => {
  875. const { content } = compile(`
  876. <script setup lang="ts">
  877. export type Emits = { (e: 'foo' | 'bar'): void }
  878. const emit = defineEmits<Emits>()
  879. </script>
  880. `)
  881. assertCode(content)
  882. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  883. expect(content).toMatch(`emits: ["foo", "bar"]`)
  884. })
  885. test('defineEmits w/ type (referenced function type)', () => {
  886. const { content } = compile(`
  887. <script setup lang="ts">
  888. type Emits = (e: 'foo' | 'bar') => void
  889. const emit = defineEmits<Emits>()
  890. </script>
  891. `)
  892. assertCode(content)
  893. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  894. expect(content).toMatch(`emits: ["foo", "bar"]`)
  895. })
  896. test('defineEmits w/ type (referenced exported function type)', () => {
  897. const { content } = compile(`
  898. <script setup lang="ts">
  899. export type Emits = (e: 'foo' | 'bar') => void
  900. const emit = defineEmits<Emits>()
  901. </script>
  902. `)
  903. assertCode(content)
  904. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  905. expect(content).toMatch(`emits: ["foo", "bar"]`)
  906. })
  907. test('runtime Enum', () => {
  908. const { content, bindings } = compile(
  909. `<script setup lang="ts">
  910. enum Foo { A = 123 }
  911. </script>`
  912. )
  913. assertCode(content)
  914. expect(bindings).toStrictEqual({
  915. Foo: BindingTypes.SETUP_CONST
  916. })
  917. })
  918. test('const Enum', () => {
  919. const { content, bindings } = compile(
  920. `<script setup lang="ts">
  921. const enum Foo { A = 123 }
  922. </script>`
  923. )
  924. assertCode(content)
  925. expect(bindings).toStrictEqual({
  926. Foo: BindingTypes.SETUP_CONST
  927. })
  928. })
  929. })
  930. describe('async/await detection', () => {
  931. function assertAwaitDetection(
  932. code: string,
  933. expected: string | ((content: string) => boolean),
  934. shouldAsync = true
  935. ) {
  936. const { content } = compile(`<script setup>${code}</script>`, {
  937. refSugar: true
  938. })
  939. if (shouldAsync) {
  940. expect(content).toMatch(`let __temp, __restore`)
  941. }
  942. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  943. if (typeof expected === 'string') {
  944. expect(content).toMatch(expected)
  945. } else {
  946. expect(expected(content)).toBe(true)
  947. }
  948. }
  949. test('expression statement', () => {
  950. assertAwaitDetection(
  951. `await foo`,
  952. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  953. )
  954. })
  955. test('variable', () => {
  956. assertAwaitDetection(
  957. `const a = 1 + (await foo)`,
  958. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  959. )
  960. })
  961. test('ref', () => {
  962. assertAwaitDetection(
  963. `let a = $ref(1 + (await foo))`,
  964. `1 + ((([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore(),__temp))`
  965. )
  966. })
  967. test('nested statements', () => {
  968. assertAwaitDetection(`if (ok) { await foo } else { await bar }`, code => {
  969. return (
  970. code.includes(
  971. `;(([__temp,__restore]=_withAsyncContext(()=>(foo))),__temp=await __temp,__restore())`
  972. ) &&
  973. code.includes(
  974. `;(([__temp,__restore]=_withAsyncContext(()=>(bar))),__temp=await __temp,__restore())`
  975. )
  976. )
  977. })
  978. })
  979. test('should ignore await inside functions', () => {
  980. // function declaration
  981. assertAwaitDetection(
  982. `async function foo() { await bar }`,
  983. `await bar`,
  984. false
  985. )
  986. // function expression
  987. assertAwaitDetection(
  988. `const foo = async () => { await bar }`,
  989. `await bar`,
  990. false
  991. )
  992. // object method
  993. assertAwaitDetection(
  994. `const obj = { async method() { await bar }}`,
  995. `await bar`,
  996. false
  997. )
  998. // class method
  999. assertAwaitDetection(
  1000. `const cls = class Foo { async method() { await bar }}`,
  1001. `await bar`,
  1002. false
  1003. )
  1004. })
  1005. })
  1006. describe('errors', () => {
  1007. test('<script> and <script setup> must have same lang', () => {
  1008. expect(() =>
  1009. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1010. ).toThrow(`<script> and <script setup> must have the same language type`)
  1011. })
  1012. const moduleErrorMsg = `cannot contain ES module exports`
  1013. test('non-type named exports', () => {
  1014. expect(() =>
  1015. compile(`<script setup>
  1016. export const a = 1
  1017. </script>`)
  1018. ).toThrow(moduleErrorMsg)
  1019. expect(() =>
  1020. compile(`<script setup>
  1021. export * from './foo'
  1022. </script>`)
  1023. ).toThrow(moduleErrorMsg)
  1024. expect(() =>
  1025. compile(`<script setup>
  1026. const bar = 1
  1027. export { bar as default }
  1028. </script>`)
  1029. ).toThrow(moduleErrorMsg)
  1030. })
  1031. test('defineProps/Emit() w/ both type and non-type args', () => {
  1032. expect(() => {
  1033. compile(`<script setup lang="ts">
  1034. defineProps<{}>({})
  1035. </script>`)
  1036. }).toThrow(`cannot accept both type and non-type arguments`)
  1037. expect(() => {
  1038. compile(`<script setup lang="ts">
  1039. defineEmits<{}>({})
  1040. </script>`)
  1041. }).toThrow(`cannot accept both type and non-type arguments`)
  1042. })
  1043. test('defineProps/Emit() referencing local var', () => {
  1044. expect(() =>
  1045. compile(`<script setup>
  1046. const bar = 1
  1047. defineProps({
  1048. foo: {
  1049. default: () => bar
  1050. }
  1051. })
  1052. </script>`)
  1053. ).toThrow(`cannot reference locally declared variables`)
  1054. expect(() =>
  1055. compile(`<script setup>
  1056. const bar = 'hello'
  1057. defineEmits([bar])
  1058. </script>`)
  1059. ).toThrow(`cannot reference locally declared variables`)
  1060. })
  1061. test('should allow defineProps/Emit() referencing scope var', () => {
  1062. assertCode(
  1063. compile(`<script setup>
  1064. const bar = 1
  1065. defineProps({
  1066. foo: {
  1067. default: bar => bar + 1
  1068. }
  1069. })
  1070. defineEmits({
  1071. foo: bar => bar > 1
  1072. })
  1073. </script>`).content
  1074. )
  1075. })
  1076. test('should allow defineProps/Emit() referencing imported binding', () => {
  1077. assertCode(
  1078. compile(`<script setup>
  1079. import { bar } from './bar'
  1080. defineProps({
  1081. foo: {
  1082. default: () => bar
  1083. }
  1084. })
  1085. defineEmits({
  1086. foo: () => bar > 1
  1087. })
  1088. </script>`).content
  1089. )
  1090. })
  1091. })
  1092. })
  1093. describe('SFC analyze <script> bindings', () => {
  1094. it('can parse decorators syntax in typescript block', () => {
  1095. const { scriptAst } = compile(`
  1096. <script lang="ts">
  1097. import { Options, Vue } from 'vue-class-component';
  1098. @Options({
  1099. components: {
  1100. HelloWorld,
  1101. },
  1102. props: ['foo', 'bar']
  1103. })
  1104. export default class Home extends Vue {}
  1105. </script>
  1106. `)
  1107. expect(scriptAst).toBeDefined()
  1108. })
  1109. it('recognizes props array declaration', () => {
  1110. const { bindings } = compile(`
  1111. <script>
  1112. export default {
  1113. props: ['foo', 'bar']
  1114. }
  1115. </script>
  1116. `)
  1117. expect(bindings).toStrictEqual({
  1118. foo: BindingTypes.PROPS,
  1119. bar: BindingTypes.PROPS
  1120. })
  1121. expect(bindings!.__isScriptSetup).toBe(false)
  1122. })
  1123. it('recognizes props object declaration', () => {
  1124. const { bindings } = compile(`
  1125. <script>
  1126. export default {
  1127. props: {
  1128. foo: String,
  1129. bar: {
  1130. type: String,
  1131. },
  1132. baz: null,
  1133. qux: [String, Number]
  1134. }
  1135. }
  1136. </script>
  1137. `)
  1138. expect(bindings).toStrictEqual({
  1139. foo: BindingTypes.PROPS,
  1140. bar: BindingTypes.PROPS,
  1141. baz: BindingTypes.PROPS,
  1142. qux: BindingTypes.PROPS
  1143. })
  1144. expect(bindings!.__isScriptSetup).toBe(false)
  1145. })
  1146. it('recognizes setup return', () => {
  1147. const { bindings } = compile(`
  1148. <script>
  1149. const bar = 2
  1150. export default {
  1151. setup() {
  1152. return {
  1153. foo: 1,
  1154. bar
  1155. }
  1156. }
  1157. }
  1158. </script>
  1159. `)
  1160. expect(bindings).toStrictEqual({
  1161. foo: BindingTypes.SETUP_MAYBE_REF,
  1162. bar: BindingTypes.SETUP_MAYBE_REF
  1163. })
  1164. expect(bindings!.__isScriptSetup).toBe(false)
  1165. })
  1166. it('recognizes async setup return', () => {
  1167. const { bindings } = compile(`
  1168. <script>
  1169. const bar = 2
  1170. export default {
  1171. async setup() {
  1172. return {
  1173. foo: 1,
  1174. bar
  1175. }
  1176. }
  1177. }
  1178. </script>
  1179. `)
  1180. expect(bindings).toStrictEqual({
  1181. foo: BindingTypes.SETUP_MAYBE_REF,
  1182. bar: BindingTypes.SETUP_MAYBE_REF
  1183. })
  1184. expect(bindings!.__isScriptSetup).toBe(false)
  1185. })
  1186. it('recognizes data return', () => {
  1187. const { bindings } = compile(`
  1188. <script>
  1189. const bar = 2
  1190. export default {
  1191. data() {
  1192. return {
  1193. foo: null,
  1194. bar
  1195. }
  1196. }
  1197. }
  1198. </script>
  1199. `)
  1200. expect(bindings).toStrictEqual({
  1201. foo: BindingTypes.DATA,
  1202. bar: BindingTypes.DATA
  1203. })
  1204. })
  1205. it('recognizes methods', () => {
  1206. const { bindings } = compile(`
  1207. <script>
  1208. export default {
  1209. methods: {
  1210. foo() {}
  1211. }
  1212. }
  1213. </script>
  1214. `)
  1215. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1216. })
  1217. it('recognizes computeds', () => {
  1218. const { bindings } = compile(`
  1219. <script>
  1220. export default {
  1221. computed: {
  1222. foo() {},
  1223. bar: {
  1224. get() {},
  1225. set() {},
  1226. }
  1227. }
  1228. }
  1229. </script>
  1230. `)
  1231. expect(bindings).toStrictEqual({
  1232. foo: BindingTypes.OPTIONS,
  1233. bar: BindingTypes.OPTIONS
  1234. })
  1235. })
  1236. it('recognizes injections array declaration', () => {
  1237. const { bindings } = compile(`
  1238. <script>
  1239. export default {
  1240. inject: ['foo', 'bar']
  1241. }
  1242. </script>
  1243. `)
  1244. expect(bindings).toStrictEqual({
  1245. foo: BindingTypes.OPTIONS,
  1246. bar: BindingTypes.OPTIONS
  1247. })
  1248. })
  1249. it('recognizes injections object declaration', () => {
  1250. const { bindings } = compile(`
  1251. <script>
  1252. export default {
  1253. inject: {
  1254. foo: {},
  1255. bar: {},
  1256. }
  1257. }
  1258. </script>
  1259. `)
  1260. expect(bindings).toStrictEqual({
  1261. foo: BindingTypes.OPTIONS,
  1262. bar: BindingTypes.OPTIONS
  1263. })
  1264. })
  1265. it('works for mixed bindings', () => {
  1266. const { bindings } = compile(`
  1267. <script>
  1268. export default {
  1269. inject: ['foo'],
  1270. props: {
  1271. bar: String,
  1272. },
  1273. setup() {
  1274. return {
  1275. baz: null,
  1276. }
  1277. },
  1278. data() {
  1279. return {
  1280. qux: null
  1281. }
  1282. },
  1283. methods: {
  1284. quux() {}
  1285. },
  1286. computed: {
  1287. quuz() {}
  1288. }
  1289. }
  1290. </script>
  1291. `)
  1292. expect(bindings).toStrictEqual({
  1293. foo: BindingTypes.OPTIONS,
  1294. bar: BindingTypes.PROPS,
  1295. baz: BindingTypes.SETUP_MAYBE_REF,
  1296. qux: BindingTypes.DATA,
  1297. quux: BindingTypes.OPTIONS,
  1298. quuz: BindingTypes.OPTIONS
  1299. })
  1300. })
  1301. it('works for script setup', () => {
  1302. const { bindings } = compile(`
  1303. <script setup>
  1304. import { ref as r } from 'vue'
  1305. defineProps({
  1306. foo: String
  1307. })
  1308. const a = r(1)
  1309. let b = 2
  1310. const c = 3
  1311. const { d } = someFoo()
  1312. let { e } = someBar()
  1313. </script>
  1314. `)
  1315. expect(bindings).toStrictEqual({
  1316. r: BindingTypes.SETUP_CONST,
  1317. a: BindingTypes.SETUP_REF,
  1318. b: BindingTypes.SETUP_LET,
  1319. c: BindingTypes.SETUP_CONST,
  1320. d: BindingTypes.SETUP_MAYBE_REF,
  1321. e: BindingTypes.SETUP_LET,
  1322. foo: BindingTypes.PROPS
  1323. })
  1324. })
  1325. })