compileScript.spec.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import { compileSFCScript as compile, assertCode, mockId } 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('binding analysis for destructure', () => {
  37. const { content, bindings } = compile(`
  38. <script setup>
  39. const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
  40. </script>
  41. `)
  42. expect(content).toMatch('return { foo, bar, baz, y, z }')
  43. expect(bindings).toStrictEqual({
  44. foo: BindingTypes.SETUP_MAYBE_REF,
  45. bar: BindingTypes.SETUP_MAYBE_REF,
  46. baz: BindingTypes.SETUP_MAYBE_REF,
  47. y: BindingTypes.SETUP_MAYBE_REF,
  48. z: BindingTypes.SETUP_MAYBE_REF
  49. })
  50. assertCode(content)
  51. })
  52. test('defineProps()', () => {
  53. const { content, bindings } = compile(`
  54. <script setup>
  55. const props = defineProps({
  56. foo: String
  57. })
  58. const bar = 1
  59. </script>
  60. `)
  61. // should generate working code
  62. assertCode(content)
  63. // should analyze bindings
  64. expect(bindings).toStrictEqual({
  65. foo: BindingTypes.PROPS,
  66. bar: BindingTypes.SETUP_CONST,
  67. props: BindingTypes.SETUP_REACTIVE_CONST
  68. })
  69. // should remove defineOptions import and call
  70. expect(content).not.toMatch('defineProps')
  71. // should generate correct setup signature
  72. expect(content).toMatch(`setup(__props, { expose }) {`)
  73. // should assign user identifier to it
  74. expect(content).toMatch(`const props = __props`)
  75. // should include context options in default export
  76. expect(content).toMatch(`export default {
  77. props: {
  78. foo: String
  79. },`)
  80. })
  81. test('defineProps w/ external definition', () => {
  82. const { content } = compile(`
  83. <script setup>
  84. import { propsModel } from './props'
  85. const props = defineProps(propsModel)
  86. </script>
  87. `)
  88. assertCode(content)
  89. expect(content).toMatch(`export default {
  90. props: propsModel,`)
  91. })
  92. // #4764
  93. test('defineProps w/ leading code', () => {
  94. const { content } = compile(`
  95. <script setup>import { x } from './x'
  96. const props = defineProps({})
  97. </script>
  98. `)
  99. // props declaration should be inside setup, not moved along with the import
  100. expect(content).not.toMatch(`const props = __props\nimport`)
  101. assertCode(content)
  102. })
  103. test('defineEmits()', () => {
  104. const { content, bindings } = compile(`
  105. <script setup>
  106. const myEmit = defineEmits(['foo', 'bar'])
  107. </script>
  108. `)
  109. assertCode(content)
  110. expect(bindings).toStrictEqual({
  111. myEmit: BindingTypes.SETUP_CONST
  112. })
  113. // should remove defineOptions import and call
  114. expect(content).not.toMatch('defineEmits')
  115. // should generate correct setup signature
  116. expect(content).toMatch(`setup(__props, { expose, emit: myEmit }) {`)
  117. // should include context options in default export
  118. expect(content).toMatch(`export default {
  119. emits: ['foo', 'bar'],`)
  120. })
  121. test('defineProps/defineEmits in multi-variable declaration', () => {
  122. const { content } = compile(`
  123. <script setup>
  124. const props = defineProps(['item']),
  125. a = 1,
  126. emit = defineEmits(['a']);
  127. </script>
  128. `)
  129. assertCode(content)
  130. expect(content).toMatch(`const a = 1;`) // test correct removal
  131. expect(content).toMatch(`props: ['item'],`)
  132. expect(content).toMatch(`emits: ['a'],`)
  133. })
  134. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  135. const { content } = compile(`
  136. <script setup>
  137. const props = defineProps(['item']),
  138. emit = defineEmits(['a']);
  139. </script>
  140. `)
  141. assertCode(content)
  142. expect(content).toMatch(`props: ['item'],`)
  143. expect(content).toMatch(`emits: ['a'],`)
  144. })
  145. test('defineExpose()', () => {
  146. const { content } = compile(`
  147. <script setup>
  148. defineExpose({ foo: 123 })
  149. </script>
  150. `)
  151. assertCode(content)
  152. // should remove defineOptions import and call
  153. expect(content).not.toMatch('defineExpose')
  154. // should generate correct setup signature
  155. expect(content).toMatch(`setup(__props, { expose }) {`)
  156. // should replace callee
  157. expect(content).toMatch(/\bexpose\(\{ foo: 123 \}\)/)
  158. })
  159. test('<script> after <script setup> the script content not end with `\\n`', () => {
  160. const { content } = compile(`
  161. <script setup>
  162. import { x } from './x'
  163. </script>
  164. <script>const n = 1</script>
  165. `)
  166. assertCode(content)
  167. })
  168. describe('<script> and <script setup> co-usage', () => {
  169. test('script first', () => {
  170. const { content } = compile(`
  171. <script>
  172. export const n = 1
  173. export default {}
  174. </script>
  175. <script setup>
  176. import { x } from './x'
  177. x()
  178. </script>
  179. `)
  180. assertCode(content)
  181. })
  182. test('script setup first', () => {
  183. const { content } = compile(`
  184. <script setup>
  185. import { x } from './x'
  186. x()
  187. </script>
  188. <script>
  189. export const n = 1
  190. export default {}
  191. </script>
  192. `)
  193. assertCode(content)
  194. })
  195. test('script setup first, named default export', () => {
  196. const { content } = compile(`
  197. <script setup>
  198. import { x } from './x'
  199. x()
  200. </script>
  201. <script>
  202. export const n = 1
  203. const def = {}
  204. export { def as default }
  205. </script>
  206. `)
  207. assertCode(content)
  208. })
  209. // #4395
  210. test('script setup first, lang="ts", script block content export default', () => {
  211. const { content } = compile(`
  212. <script setup lang="ts">
  213. import { x } from './x'
  214. x()
  215. </script>
  216. <script lang="ts">
  217. export default {
  218. name: "test"
  219. }
  220. </script>
  221. `)
  222. // ensure __default__ is declared before used
  223. expect(content).toMatch(/const __default__[\S\s]*\.\.\.__default__/m)
  224. assertCode(content)
  225. })
  226. describe('spaces in ExportDefaultDeclaration node', () => {
  227. // #4371
  228. test('with many spaces and newline', () => {
  229. // #4371
  230. const { content } = compile(`
  231. <script>
  232. export const n = 1
  233. export default
  234. {
  235. some:'option'
  236. }
  237. </script>
  238. <script setup>
  239. import { x } from './x'
  240. x()
  241. </script>
  242. `)
  243. assertCode(content)
  244. })
  245. test('with minimal spaces', () => {
  246. const { content } = compile(`
  247. <script>
  248. export const n = 1
  249. export default{
  250. some:'option'
  251. }
  252. </script>
  253. <script setup>
  254. import { x } from './x'
  255. x()
  256. </script>
  257. `)
  258. assertCode(content)
  259. })
  260. })
  261. })
  262. describe('imports', () => {
  263. test('should hoist and expose imports', () => {
  264. assertCode(
  265. compile(`<script setup>
  266. import { ref } from 'vue'
  267. import 'foo/css'
  268. </script>`).content
  269. )
  270. })
  271. test('should extract comment for import or type declarations', () => {
  272. assertCode(
  273. compile(`
  274. <script setup>
  275. import a from 'a' // comment
  276. import b from 'b'
  277. </script>
  278. `).content
  279. )
  280. })
  281. // #2740
  282. test('should allow defineProps/Emit at the start of imports', () => {
  283. assertCode(
  284. compile(`<script setup>
  285. import { ref } from 'vue'
  286. defineProps(['foo'])
  287. defineEmits(['bar'])
  288. const r = ref(0)
  289. </script>`).content
  290. )
  291. })
  292. test('dedupe between user & helper', () => {
  293. const { content } = compile(
  294. `
  295. <script setup>
  296. import { ref } from 'vue'
  297. let foo = $ref(1)
  298. </script>
  299. `,
  300. { reactivityTransform: true }
  301. )
  302. assertCode(content)
  303. expect(content).toMatch(`import { ref } from 'vue'`)
  304. })
  305. test('import dedupe between <script> and <script setup>', () => {
  306. const { content } = compile(`
  307. <script>
  308. import { x } from './x'
  309. </script>
  310. <script setup>
  311. import { x } from './x'
  312. x()
  313. </script>
  314. `)
  315. assertCode(content)
  316. expect(content.indexOf(`import { x }`)).toEqual(
  317. content.lastIndexOf(`import { x }`)
  318. )
  319. })
  320. })
  321. // in dev mode, declared bindings are returned as an object from setup()
  322. // when using TS, users may import types which should not be returned as
  323. // values, so we need to check import usage in the template to determine
  324. // what to be returned.
  325. describe('dev mode import usage check', () => {
  326. test('components', () => {
  327. const { content } = compile(`
  328. <script setup lang="ts">
  329. import { FooBar, FooBaz, FooQux, foo } from './x'
  330. const fooBar: FooBar = 1
  331. </script>
  332. <template>
  333. <FooBaz></FooBaz>
  334. <foo-qux/>
  335. <foo/>
  336. FooBar
  337. </template>
  338. `)
  339. // FooBar: should not be matched by plain text or incorrect case
  340. // FooBaz: used as PascalCase component
  341. // FooQux: used as kebab-case component
  342. // foo: lowercase component
  343. expect(content).toMatch(`return { fooBar, FooBaz, FooQux, foo }`)
  344. assertCode(content)
  345. })
  346. test('directive', () => {
  347. const { content } = compile(`
  348. <script setup lang="ts">
  349. import { vMyDir } from './x'
  350. </script>
  351. <template>
  352. <div v-my-dir></div>
  353. </template>
  354. `)
  355. expect(content).toMatch(`return { vMyDir }`)
  356. assertCode(content)
  357. })
  358. // https://github.com/vuejs/core/issues/4599
  359. test('attribute expressions', () => {
  360. const { content } = compile(`
  361. <script setup lang="ts">
  362. import { bar, baz } from './x'
  363. const cond = true
  364. </script>
  365. <template>
  366. <div :class="[cond ? '' : bar(), 'default']" :style="baz"></div>
  367. </template>
  368. `)
  369. expect(content).toMatch(`return { cond, bar, baz }`)
  370. assertCode(content)
  371. })
  372. test('vue interpolations', () => {
  373. const { content } = compile(`
  374. <script setup lang="ts">
  375. import { x, y, z, x$y } from './x'
  376. </script>
  377. <template>
  378. <div :id="z + 'y'">{{ x }} {{ yy }} {{ x$y }}</div>
  379. </template>
  380. `)
  381. // x: used in interpolation
  382. // y: should not be matched by {{ yy }} or 'y' in binding exps
  383. // x$y: #4274 should escape special chars when creating Regex
  384. expect(content).toMatch(`return { x, z, x$y }`)
  385. assertCode(content)
  386. })
  387. // #4340 interpolations in template strings
  388. test('js template string interpolations', () => {
  389. const { content } = compile(`
  390. <script setup lang="ts">
  391. import { VAR, VAR2, VAR3 } from './x'
  392. </script>
  393. <template>
  394. {{ \`\${VAR}VAR2\${VAR3}\` }}
  395. </template>
  396. `)
  397. // VAR2 should not be matched
  398. expect(content).toMatch(`return { VAR, VAR3 }`)
  399. assertCode(content)
  400. })
  401. // edge case: last tag in template
  402. test('last tag', () => {
  403. const { content } = compile(`
  404. <script setup lang="ts">
  405. import { FooBaz, Last } from './x'
  406. </script>
  407. <template>
  408. <FooBaz></FooBaz>
  409. <Last/>
  410. </template>
  411. `)
  412. expect(content).toMatch(`return { FooBaz, Last }`)
  413. assertCode(content)
  414. })
  415. test('TS annotations', () => {
  416. const { content } = compile(`
  417. <script setup lang="ts">
  418. import { Foo, Bar, Baz, Qux, Fred } from './x'
  419. const a = 1
  420. function b() {}
  421. </script>
  422. <template>
  423. {{ a as Foo }}
  424. {{ b<Bar>() }}
  425. {{ Baz }}
  426. <Comp v-slot="{ data }: Qux">{{ data }}</Comp>
  427. <div v-for="{ z = x as Qux } in list as Fred"/>
  428. </template>
  429. `)
  430. expect(content).toMatch(`return { a, b, Baz }`)
  431. assertCode(content)
  432. })
  433. // vuejs/vue#12591
  434. test('v-on inline statement', () => {
  435. // should not error
  436. compile(`
  437. <script setup lang="ts">
  438. import { foo } from './foo'
  439. </script>
  440. <template>
  441. <div @click="$emit('update:a');"></div>
  442. </template>
  443. `)
  444. })
  445. })
  446. describe('inlineTemplate mode', () => {
  447. test('should work', () => {
  448. const { content } = compile(
  449. `
  450. <script setup>
  451. import { ref } from 'vue'
  452. const count = ref(0)
  453. </script>
  454. <template>
  455. <div>{{ count }}</div>
  456. <div>static</div>
  457. </template>
  458. `,
  459. { inlineTemplate: true }
  460. )
  461. // check snapshot and make sure helper imports and
  462. // hoists are placed correctly.
  463. assertCode(content)
  464. // in inline mode, no need to call expose() since nothing is exposed
  465. // anyway!
  466. expect(content).not.toMatch(`expose()`)
  467. })
  468. test('with defineExpose()', () => {
  469. const { content } = compile(
  470. `
  471. <script setup>
  472. const count = ref(0)
  473. defineExpose({ count })
  474. </script>
  475. `,
  476. { inlineTemplate: true }
  477. )
  478. assertCode(content)
  479. expect(content).toMatch(`setup(__props, { expose })`)
  480. expect(content).toMatch(`expose({ count })`)
  481. })
  482. test('referencing scope components and directives', () => {
  483. const { content } = compile(
  484. `
  485. <script setup>
  486. import ChildComp from './Child.vue'
  487. import SomeOtherComp from './Other.vue'
  488. import vMyDir from './my-dir'
  489. </script>
  490. <template>
  491. <div v-my-dir></div>
  492. <ChildComp/>
  493. <some-other-comp/>
  494. </template>
  495. `,
  496. { inlineTemplate: true }
  497. )
  498. expect(content).toMatch('[_unref(vMyDir)]')
  499. expect(content).toMatch('_createVNode(ChildComp)')
  500. // kebab-case component support
  501. expect(content).toMatch('_createVNode(SomeOtherComp)')
  502. assertCode(content)
  503. })
  504. test('avoid unref() when necessary', () => {
  505. // function, const, component import
  506. const { content } = compile(
  507. `<script setup>
  508. import { ref } from 'vue'
  509. import Foo, { bar } from './Foo.vue'
  510. import other from './util'
  511. import * as tree from './tree'
  512. const count = ref(0)
  513. const constant = {}
  514. const maybe = foo()
  515. let lett = 1
  516. function fn() {}
  517. </script>
  518. <template>
  519. <Foo>{{ bar }}</Foo>
  520. <div @click="fn">{{ count }} {{ constant }} {{ maybe }} {{ lett }} {{ other }}</div>
  521. {{ tree.foo() }}
  522. </template>
  523. `,
  524. { inlineTemplate: true }
  525. )
  526. // no need to unref vue component import
  527. expect(content).toMatch(`createVNode(Foo,`)
  528. // #2699 should unref named imports from .vue
  529. expect(content).toMatch(`unref(bar)`)
  530. // should unref other imports
  531. expect(content).toMatch(`unref(other)`)
  532. // no need to unref constant literals
  533. expect(content).not.toMatch(`unref(constant)`)
  534. // should directly use .value for known refs
  535. expect(content).toMatch(`count.value`)
  536. // should unref() on const bindings that may be refs
  537. expect(content).toMatch(`unref(maybe)`)
  538. // should unref() on let bindings
  539. expect(content).toMatch(`unref(lett)`)
  540. // no need to unref namespace import (this also preserves tree-shaking)
  541. expect(content).toMatch(`tree.foo()`)
  542. // no need to unref function declarations
  543. expect(content).toMatch(`{ onClick: fn }`)
  544. // no need to mark constant fns in patch flag
  545. expect(content).not.toMatch(`PROPS`)
  546. assertCode(content)
  547. })
  548. test('v-model codegen', () => {
  549. const { content } = compile(
  550. `<script setup>
  551. import { ref } from 'vue'
  552. const count = ref(0)
  553. const maybe = foo()
  554. let lett = 1
  555. </script>
  556. <template>
  557. <input v-model="count">
  558. <input v-model="maybe">
  559. <input v-model="lett">
  560. </template>
  561. `,
  562. { inlineTemplate: true }
  563. )
  564. // known const ref: set value
  565. expect(content).toMatch(`(count).value = $event`)
  566. // const but maybe ref: assign if ref, otherwise do nothing
  567. expect(content).toMatch(`_isRef(maybe) ? (maybe).value = $event : null`)
  568. // let: handle both cases
  569. expect(content).toMatch(
  570. `_isRef(lett) ? (lett).value = $event : lett = $event`
  571. )
  572. assertCode(content)
  573. })
  574. test('template assignment expression codegen', () => {
  575. const { content } = compile(
  576. `<script setup>
  577. import { ref } from 'vue'
  578. const count = ref(0)
  579. const maybe = foo()
  580. let lett = 1
  581. let v = ref(1)
  582. </script>
  583. <template>
  584. <div @click="count = 1"/>
  585. <div @click="maybe = count"/>
  586. <div @click="lett = count"/>
  587. <div @click="v += 1"/>
  588. <div @click="v -= 1"/>
  589. <div @click="() => {
  590. let a = '' + lett
  591. v = a
  592. }"/>
  593. <div @click="() => {
  594. // nested scopes
  595. (()=>{
  596. let x = a
  597. (()=>{
  598. let z = x
  599. let z2 = z
  600. })
  601. let lz = z
  602. })
  603. v = a
  604. }"/>
  605. </template>
  606. `,
  607. { inlineTemplate: true }
  608. )
  609. // known const ref: set value
  610. expect(content).toMatch(`count.value = 1`)
  611. // const but maybe ref: only assign after check
  612. expect(content).toMatch(`maybe.value = count.value`)
  613. // let: handle both cases
  614. expect(content).toMatch(
  615. `_isRef(lett) ? lett.value = count.value : lett = count.value`
  616. )
  617. expect(content).toMatch(`_isRef(v) ? v.value += 1 : v += 1`)
  618. expect(content).toMatch(`_isRef(v) ? v.value -= 1 : v -= 1`)
  619. expect(content).toMatch(`_isRef(v) ? v.value = a : v = a`)
  620. expect(content).toMatch(`_isRef(v) ? v.value = _ctx.a : v = _ctx.a`)
  621. assertCode(content)
  622. })
  623. test('template update expression codegen', () => {
  624. const { content } = compile(
  625. `<script setup>
  626. import { ref } from 'vue'
  627. const count = ref(0)
  628. const maybe = foo()
  629. let lett = 1
  630. </script>
  631. <template>
  632. <div @click="count++"/>
  633. <div @click="--count"/>
  634. <div @click="maybe++"/>
  635. <div @click="--maybe"/>
  636. <div @click="lett++"/>
  637. <div @click="--lett"/>
  638. </template>
  639. `,
  640. { inlineTemplate: true }
  641. )
  642. // known const ref: set value
  643. expect(content).toMatch(`count.value++`)
  644. expect(content).toMatch(`--count.value`)
  645. // const but maybe ref (non-ref case ignored)
  646. expect(content).toMatch(`maybe.value++`)
  647. expect(content).toMatch(`--maybe.value`)
  648. // let: handle both cases
  649. expect(content).toMatch(`_isRef(lett) ? lett.value++ : lett++`)
  650. expect(content).toMatch(`_isRef(lett) ? --lett.value : --lett`)
  651. assertCode(content)
  652. })
  653. test('template destructure assignment codegen', () => {
  654. const { content } = compile(
  655. `<script setup>
  656. import { ref } from 'vue'
  657. const val = {}
  658. const count = ref(0)
  659. const maybe = foo()
  660. let lett = 1
  661. </script>
  662. <template>
  663. <div @click="({ count } = val)"/>
  664. <div @click="[maybe] = val"/>
  665. <div @click="({ lett } = val)"/>
  666. </template>
  667. `,
  668. { inlineTemplate: true }
  669. )
  670. // known const ref: set value
  671. expect(content).toMatch(`({ count: count.value } = val)`)
  672. // const but maybe ref (non-ref case ignored)
  673. expect(content).toMatch(`[maybe.value] = val`)
  674. // let: assumes non-ref
  675. expect(content).toMatch(`{ lett: lett } = val`)
  676. assertCode(content)
  677. })
  678. test('ssr codegen', () => {
  679. const { content } = compile(
  680. `
  681. <script setup>
  682. import { ref } from 'vue'
  683. const count = ref(0)
  684. </script>
  685. <template>
  686. <div>{{ count }}</div>
  687. <div>static</div>
  688. </template>
  689. <style>
  690. div { color: v-bind(count) }
  691. </style>
  692. `,
  693. {
  694. inlineTemplate: true,
  695. templateOptions: {
  696. ssr: true
  697. }
  698. }
  699. )
  700. expect(content).toMatch(`\n __ssrInlineRender: true,\n`)
  701. expect(content).toMatch(`return (_ctx, _push`)
  702. expect(content).toMatch(`ssrInterpolate`)
  703. expect(content).not.toMatch(`useCssVars`)
  704. expect(content).toMatch(`"--${mockId}-count": (count.value)`)
  705. assertCode(content)
  706. })
  707. })
  708. describe('with TypeScript', () => {
  709. test('hoist type declarations', () => {
  710. const { content } = compile(`
  711. <script setup lang="ts">
  712. export interface Foo {}
  713. type Bar = {}
  714. </script>`)
  715. assertCode(content)
  716. })
  717. test('defineProps/Emit w/ runtime options', () => {
  718. const { content } = compile(`
  719. <script setup lang="ts">
  720. const props = defineProps({ foo: String })
  721. const emit = defineEmits(['a', 'b'])
  722. </script>
  723. `)
  724. assertCode(content)
  725. expect(content).toMatch(`export default /*#__PURE__*/_defineComponent({
  726. props: { foo: String },
  727. emits: ['a', 'b'],
  728. setup(__props, { expose, emit }) {`)
  729. })
  730. test('defineProps w/ type', () => {
  731. const { content, bindings } = compile(`
  732. <script setup lang="ts">
  733. interface Test {}
  734. type Alias = number[]
  735. defineProps<{
  736. string: string
  737. number: number
  738. boolean: boolean
  739. object: object
  740. objectLiteral: { a: number }
  741. fn: (n: number) => void
  742. functionRef: Function
  743. objectRef: Object
  744. dateTime: Date
  745. array: string[]
  746. arrayRef: Array<any>
  747. tuple: [number, number]
  748. set: Set<string>
  749. literal: 'foo'
  750. optional?: any
  751. recordRef: Record<string, null>
  752. interface: Test
  753. alias: Alias
  754. method(): void
  755. symbol: symbol
  756. union: string | number
  757. literalUnion: 'foo' | 'bar'
  758. literalUnionNumber: 1 | 2 | 3 | 4 | 5
  759. literalUnionMixed: 'foo' | 1 | boolean
  760. intersection: Test & {}
  761. foo: ((item: any) => boolean) | null
  762. }>()
  763. </script>`)
  764. assertCode(content)
  765. expect(content).toMatch(`string: { type: String, required: true }`)
  766. expect(content).toMatch(`number: { type: Number, required: true }`)
  767. expect(content).toMatch(`boolean: { type: Boolean, required: true }`)
  768. expect(content).toMatch(`object: { type: Object, required: true }`)
  769. expect(content).toMatch(`objectLiteral: { type: Object, required: true }`)
  770. expect(content).toMatch(`fn: { type: Function, required: true }`)
  771. expect(content).toMatch(`functionRef: { type: Function, required: true }`)
  772. expect(content).toMatch(`objectRef: { type: Object, required: true }`)
  773. expect(content).toMatch(`dateTime: { type: Date, required: true }`)
  774. expect(content).toMatch(`array: { type: Array, required: true }`)
  775. expect(content).toMatch(`arrayRef: { type: Array, required: true }`)
  776. expect(content).toMatch(`tuple: { type: Array, required: true }`)
  777. expect(content).toMatch(`set: { type: Set, required: true }`)
  778. expect(content).toMatch(`literal: { type: String, required: true }`)
  779. expect(content).toMatch(`optional: { type: null, required: false }`)
  780. expect(content).toMatch(`recordRef: { type: Object, required: true }`)
  781. expect(content).toMatch(`interface: { type: Object, required: true }`)
  782. expect(content).toMatch(`alias: { type: Array, required: true }`)
  783. expect(content).toMatch(`method: { type: Function, required: true }`)
  784. expect(content).toMatch(`symbol: { type: Symbol, required: true }`)
  785. expect(content).toMatch(
  786. `union: { type: [String, Number], required: true }`
  787. )
  788. expect(content).toMatch(`literalUnion: { type: String, required: true }`)
  789. expect(content).toMatch(
  790. `literalUnionNumber: { type: Number, required: true }`
  791. )
  792. expect(content).toMatch(
  793. `literalUnionMixed: { type: [String, Number, Boolean], required: true }`
  794. )
  795. expect(content).toMatch(`intersection: { type: Object, required: true }`)
  796. expect(content).toMatch(`foo: { type: [Function, null], required: true }`)
  797. expect(bindings).toStrictEqual({
  798. string: BindingTypes.PROPS,
  799. number: BindingTypes.PROPS,
  800. boolean: BindingTypes.PROPS,
  801. object: BindingTypes.PROPS,
  802. objectLiteral: BindingTypes.PROPS,
  803. fn: BindingTypes.PROPS,
  804. functionRef: BindingTypes.PROPS,
  805. objectRef: BindingTypes.PROPS,
  806. dateTime: BindingTypes.PROPS,
  807. array: BindingTypes.PROPS,
  808. arrayRef: BindingTypes.PROPS,
  809. tuple: BindingTypes.PROPS,
  810. set: BindingTypes.PROPS,
  811. literal: BindingTypes.PROPS,
  812. optional: BindingTypes.PROPS,
  813. recordRef: BindingTypes.PROPS,
  814. interface: BindingTypes.PROPS,
  815. alias: BindingTypes.PROPS,
  816. method: BindingTypes.PROPS,
  817. symbol: BindingTypes.PROPS,
  818. union: BindingTypes.PROPS,
  819. literalUnion: BindingTypes.PROPS,
  820. literalUnionNumber: BindingTypes.PROPS,
  821. literalUnionMixed: BindingTypes.PROPS,
  822. intersection: BindingTypes.PROPS,
  823. foo: BindingTypes.PROPS
  824. })
  825. })
  826. test('defineProps w/ interface', () => {
  827. const { content, bindings } = compile(`
  828. <script setup lang="ts">
  829. interface Props { x?: number }
  830. defineProps<Props>()
  831. </script>
  832. `)
  833. assertCode(content)
  834. expect(content).toMatch(`x: { type: Number, required: false }`)
  835. expect(bindings).toStrictEqual({
  836. x: BindingTypes.PROPS
  837. })
  838. })
  839. test('defineProps w/ extends interface', () => {
  840. const { content, bindings } = compile(`
  841. <script lang="ts">
  842. interface Foo { x?: number }
  843. </script>
  844. <script setup lang="ts">
  845. interface Bar extends Foo { y?: number }
  846. interface Props extends Bar {
  847. z: number
  848. y: string
  849. }
  850. defineProps<Props>()
  851. </script>
  852. `)
  853. assertCode(content)
  854. expect(content).toMatch(`z: { type: Number, required: true }`)
  855. expect(content).toMatch(`y: { type: String, required: true }`)
  856. expect(content).toMatch(`x: { type: Number, required: false }`)
  857. expect(bindings).toStrictEqual({
  858. x: BindingTypes.PROPS,
  859. y: BindingTypes.PROPS,
  860. z: BindingTypes.PROPS
  861. })
  862. })
  863. test('defineProps w/ exported interface', () => {
  864. const { content, bindings } = compile(`
  865. <script setup lang="ts">
  866. export interface Props { x?: number }
  867. defineProps<Props>()
  868. </script>
  869. `)
  870. assertCode(content)
  871. expect(content).toMatch(`x: { type: Number, required: false }`)
  872. expect(bindings).toStrictEqual({
  873. x: BindingTypes.PROPS
  874. })
  875. })
  876. test('defineProps w/ exported interface in normal script', () => {
  877. const { content, bindings } = compile(`
  878. <script lang="ts">
  879. export interface Props { x?: number }
  880. </script>
  881. <script setup lang="ts">
  882. defineProps<Props>()
  883. </script>
  884. `)
  885. assertCode(content)
  886. expect(content).toMatch(`x: { type: Number, required: false }`)
  887. expect(bindings).toStrictEqual({
  888. x: BindingTypes.PROPS
  889. })
  890. })
  891. test('defineProps w/ type alias', () => {
  892. const { content, bindings } = compile(`
  893. <script setup lang="ts">
  894. type Props = { x?: number }
  895. defineProps<Props>()
  896. </script>
  897. `)
  898. assertCode(content)
  899. expect(content).toMatch(`x: { type: Number, required: false }`)
  900. expect(bindings).toStrictEqual({
  901. x: BindingTypes.PROPS
  902. })
  903. })
  904. test('defineProps w/ exported type alias', () => {
  905. const { content, bindings } = compile(`
  906. <script setup lang="ts">
  907. export type Props = { x?: number }
  908. defineProps<Props>()
  909. </script>
  910. `)
  911. assertCode(content)
  912. expect(content).toMatch(`x: { type: Number, required: false }`)
  913. expect(bindings).toStrictEqual({
  914. x: BindingTypes.PROPS
  915. })
  916. })
  917. test('withDefaults (static)', () => {
  918. const { content, bindings } = compile(`
  919. <script setup lang="ts">
  920. const props = withDefaults(defineProps<{
  921. foo?: string
  922. bar?: number;
  923. baz: boolean;
  924. qux?(): number
  925. }>(), {
  926. foo: 'hi',
  927. qux() { return 1 }
  928. })
  929. </script>
  930. `)
  931. assertCode(content)
  932. expect(content).toMatch(
  933. `foo: { type: String, required: false, default: 'hi' }`
  934. )
  935. expect(content).toMatch(`bar: { type: Number, required: false }`)
  936. expect(content).toMatch(`baz: { type: Boolean, required: true }`)
  937. expect(content).toMatch(
  938. `qux: { type: Function, required: false, default() { return 1 } }`
  939. )
  940. expect(content).toMatch(
  941. `{ foo: string, bar?: number, baz: boolean, qux(): number }`
  942. )
  943. expect(content).toMatch(`const props = __props`)
  944. expect(bindings).toStrictEqual({
  945. foo: BindingTypes.PROPS,
  946. bar: BindingTypes.PROPS,
  947. baz: BindingTypes.PROPS,
  948. qux: BindingTypes.PROPS,
  949. props: BindingTypes.SETUP_CONST
  950. })
  951. })
  952. test('withDefaults (dynamic)', () => {
  953. const { content } = compile(`
  954. <script setup lang="ts">
  955. import { defaults } from './foo'
  956. const props = withDefaults(defineProps<{
  957. foo?: string
  958. bar?: number
  959. baz: boolean
  960. }>(), { ...defaults })
  961. </script>
  962. `)
  963. assertCode(content)
  964. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  965. expect(content).toMatch(
  966. `
  967. _mergeDefaults({
  968. foo: { type: String, required: false },
  969. bar: { type: Number, required: false },
  970. baz: { type: Boolean, required: true }
  971. }, { ...defaults })`.trim()
  972. )
  973. })
  974. test('defineEmits w/ type', () => {
  975. const { content } = compile(`
  976. <script setup lang="ts">
  977. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  978. </script>
  979. `)
  980. assertCode(content)
  981. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  982. expect(content).toMatch(`emits: ["foo", "bar"]`)
  983. })
  984. test('defineEmits w/ type (union)', () => {
  985. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  986. expect(() =>
  987. compile(`
  988. <script setup lang="ts">
  989. const emit = defineEmits<${type}>()
  990. </script>
  991. `)
  992. ).toThrow()
  993. })
  994. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  995. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  996. const { content } = compile(`
  997. <script setup lang="ts">
  998. const emit = defineEmits<${type}>()
  999. </script>
  1000. `)
  1001. assertCode(content)
  1002. expect(content).toMatch(`emit: (${type}),`)
  1003. expect(content).toMatch(`emits: ["foo", "bar", "baz"]`)
  1004. })
  1005. test('defineEmits w/ type (interface)', () => {
  1006. const { content } = compile(`
  1007. <script setup lang="ts">
  1008. interface Emits { (e: 'foo' | 'bar'): void }
  1009. const emit = defineEmits<Emits>()
  1010. </script>
  1011. `)
  1012. assertCode(content)
  1013. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1014. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1015. })
  1016. test('defineEmits w/ type (exported interface)', () => {
  1017. const { content } = compile(`
  1018. <script setup lang="ts">
  1019. export interface Emits { (e: 'foo' | 'bar'): void }
  1020. const emit = defineEmits<Emits>()
  1021. </script>
  1022. `)
  1023. assertCode(content)
  1024. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1025. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1026. })
  1027. test('defineEmits w/ type (type alias)', () => {
  1028. const { content } = compile(`
  1029. <script setup lang="ts">
  1030. type Emits = { (e: 'foo' | 'bar'): void }
  1031. const emit = defineEmits<Emits>()
  1032. </script>
  1033. `)
  1034. assertCode(content)
  1035. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1036. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1037. })
  1038. test('defineEmits w/ type (exported type alias)', () => {
  1039. const { content } = compile(`
  1040. <script setup lang="ts">
  1041. export type Emits = { (e: 'foo' | 'bar'): void }
  1042. const emit = defineEmits<Emits>()
  1043. </script>
  1044. `)
  1045. assertCode(content)
  1046. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1047. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1048. })
  1049. test('defineEmits w/ type (referenced function type)', () => {
  1050. const { content } = compile(`
  1051. <script setup lang="ts">
  1052. type Emits = (e: 'foo' | 'bar') => void
  1053. const emit = defineEmits<Emits>()
  1054. </script>
  1055. `)
  1056. assertCode(content)
  1057. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1058. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1059. })
  1060. test('defineEmits w/ type (referenced exported function type)', () => {
  1061. const { content } = compile(`
  1062. <script setup lang="ts">
  1063. export type Emits = (e: 'foo' | 'bar') => void
  1064. const emit = defineEmits<Emits>()
  1065. </script>
  1066. `)
  1067. assertCode(content)
  1068. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1069. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1070. })
  1071. test('runtime Enum', () => {
  1072. const { content, bindings } = compile(
  1073. `<script setup lang="ts">
  1074. enum Foo { A = 123 }
  1075. </script>`
  1076. )
  1077. assertCode(content)
  1078. expect(bindings).toStrictEqual({
  1079. Foo: BindingTypes.SETUP_CONST
  1080. })
  1081. })
  1082. test('runtime Enum in normal script', () => {
  1083. const { content, bindings } = compile(
  1084. `<script lang="ts">
  1085. export enum D { D = "D" }
  1086. const enum C { C = "C" }
  1087. enum B { B = "B" }
  1088. </script>
  1089. <script setup lang="ts">
  1090. enum Foo { A = 123 }
  1091. </script>`
  1092. )
  1093. assertCode(content)
  1094. expect(bindings).toStrictEqual({
  1095. D: BindingTypes.SETUP_CONST,
  1096. C: BindingTypes.SETUP_CONST,
  1097. B: BindingTypes.SETUP_CONST,
  1098. Foo: BindingTypes.SETUP_CONST
  1099. })
  1100. })
  1101. test('const Enum', () => {
  1102. const { content, bindings } = compile(
  1103. `<script setup lang="ts">
  1104. const enum Foo { A = 123 }
  1105. </script>`
  1106. )
  1107. assertCode(content)
  1108. expect(bindings).toStrictEqual({
  1109. Foo: BindingTypes.SETUP_CONST
  1110. })
  1111. })
  1112. test('import type', () => {
  1113. const { content } = compile(
  1114. `<script setup lang="ts">
  1115. import type { Foo } from './main.ts'
  1116. import { type Bar, Baz } from './main.ts'
  1117. </script>`
  1118. )
  1119. expect(content).toMatch(`return { Baz }`)
  1120. assertCode(content)
  1121. })
  1122. })
  1123. describe('async/await detection', () => {
  1124. function assertAwaitDetection(code: string, shouldAsync = true) {
  1125. const { content } = compile(`<script setup>${code}</script>`, {
  1126. reactivityTransform: true
  1127. })
  1128. if (shouldAsync) {
  1129. expect(content).toMatch(`let __temp, __restore`)
  1130. }
  1131. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  1132. assertCode(content)
  1133. return content
  1134. }
  1135. test('expression statement', () => {
  1136. assertAwaitDetection(`await foo`)
  1137. })
  1138. test('variable', () => {
  1139. assertAwaitDetection(`const a = 1 + (await foo)`)
  1140. })
  1141. test('ref', () => {
  1142. assertAwaitDetection(`let a = $ref(1 + (await foo))`)
  1143. })
  1144. // #4448
  1145. test('nested await', () => {
  1146. assertAwaitDetection(`await (await foo)`)
  1147. assertAwaitDetection(`await ((await foo))`)
  1148. assertAwaitDetection(`await (await (await foo))`)
  1149. })
  1150. // should prepend semicolon
  1151. test('nested leading await in expression statement', () => {
  1152. const code = assertAwaitDetection(`foo()\nawait 1 + await 2`)
  1153. expect(code).toMatch(`foo()\n;(`)
  1154. })
  1155. // #4596 should NOT prepend semicolon
  1156. test('single line conditions', () => {
  1157. const code = assertAwaitDetection(`if (false) await foo()`)
  1158. expect(code).not.toMatch(`if (false) ;(`)
  1159. })
  1160. test('nested statements', () => {
  1161. assertAwaitDetection(`if (ok) { await foo } else { await bar }`)
  1162. })
  1163. test('multiple `if` nested statements', () => {
  1164. assertAwaitDetection(`if (ok) {
  1165. let a = 'foo'
  1166. await 0 + await 1
  1167. await 2
  1168. } else if (a) {
  1169. await 10
  1170. if (b) {
  1171. await 0 + await 1
  1172. } else {
  1173. let a = 'foo'
  1174. await 2
  1175. }
  1176. if (b) {
  1177. await 3
  1178. await 4
  1179. }
  1180. } else {
  1181. await 5
  1182. }`)
  1183. })
  1184. test('multiple `if while` nested statements', () => {
  1185. assertAwaitDetection(`if (ok) {
  1186. while (d) {
  1187. await 5
  1188. }
  1189. while (d) {
  1190. await 5
  1191. await 6
  1192. if (c) {
  1193. let f = 10
  1194. 10 + await 7
  1195. } else {
  1196. await 8
  1197. await 9
  1198. }
  1199. }
  1200. }`)
  1201. })
  1202. test('multiple `if for` nested statements', () => {
  1203. assertAwaitDetection(`if (ok) {
  1204. for (let a of [1,2,3]) {
  1205. await a
  1206. }
  1207. for (let a of [1,2,3]) {
  1208. await a
  1209. await a
  1210. }
  1211. }`)
  1212. })
  1213. test('should ignore await inside functions', () => {
  1214. // function declaration
  1215. assertAwaitDetection(`async function foo() { await bar }`, false)
  1216. // function expression
  1217. assertAwaitDetection(`const foo = async () => { await bar }`, false)
  1218. // object method
  1219. assertAwaitDetection(`const obj = { async method() { await bar }}`, false)
  1220. // class method
  1221. assertAwaitDetection(
  1222. `const cls = class Foo { async method() { await bar }}`,
  1223. false
  1224. )
  1225. })
  1226. })
  1227. describe('errors', () => {
  1228. test('<script> and <script setup> must have same lang', () => {
  1229. expect(() =>
  1230. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1231. ).toThrow(`<script> and <script setup> must have the same language type`)
  1232. })
  1233. const moduleErrorMsg = `cannot contain ES module exports`
  1234. test('non-type named exports', () => {
  1235. expect(() =>
  1236. compile(`<script setup>
  1237. export const a = 1
  1238. </script>`)
  1239. ).toThrow(moduleErrorMsg)
  1240. expect(() =>
  1241. compile(`<script setup>
  1242. export * from './foo'
  1243. </script>`)
  1244. ).toThrow(moduleErrorMsg)
  1245. expect(() =>
  1246. compile(`<script setup>
  1247. const bar = 1
  1248. export { bar as default }
  1249. </script>`)
  1250. ).toThrow(moduleErrorMsg)
  1251. })
  1252. test('defineProps/Emit() w/ both type and non-type args', () => {
  1253. expect(() => {
  1254. compile(`<script setup lang="ts">
  1255. defineProps<{}>({})
  1256. </script>`)
  1257. }).toThrow(`cannot accept both type and non-type arguments`)
  1258. expect(() => {
  1259. compile(`<script setup lang="ts">
  1260. defineEmits<{}>({})
  1261. </script>`)
  1262. }).toThrow(`cannot accept both type and non-type arguments`)
  1263. })
  1264. test('defineProps/Emit() referencing local var', () => {
  1265. expect(() =>
  1266. compile(`<script setup>
  1267. const bar = 1
  1268. defineProps({
  1269. foo: {
  1270. default: () => bar
  1271. }
  1272. })
  1273. </script>`)
  1274. ).toThrow(`cannot reference locally declared variables`)
  1275. expect(() =>
  1276. compile(`<script setup>
  1277. const bar = 'hello'
  1278. defineEmits([bar])
  1279. </script>`)
  1280. ).toThrow(`cannot reference locally declared variables`)
  1281. // #4644
  1282. expect(() =>
  1283. compile(`
  1284. <script>const bar = 1</script>
  1285. <script setup>
  1286. defineProps({
  1287. foo: {
  1288. default: () => bar
  1289. }
  1290. })
  1291. </script>`)
  1292. ).not.toThrow(`cannot reference locally declared variables`)
  1293. })
  1294. test('should allow defineProps/Emit() referencing scope var', () => {
  1295. assertCode(
  1296. compile(`<script setup>
  1297. const bar = 1
  1298. defineProps({
  1299. foo: {
  1300. default: bar => bar + 1
  1301. }
  1302. })
  1303. defineEmits({
  1304. foo: bar => bar > 1
  1305. })
  1306. </script>`).content
  1307. )
  1308. })
  1309. test('should allow defineProps/Emit() referencing imported binding', () => {
  1310. assertCode(
  1311. compile(`<script setup>
  1312. import { bar } from './bar'
  1313. defineProps({
  1314. foo: {
  1315. default: () => bar
  1316. }
  1317. })
  1318. defineEmits({
  1319. foo: () => bar > 1
  1320. })
  1321. </script>`).content
  1322. )
  1323. })
  1324. })
  1325. })
  1326. describe('SFC analyze <script> bindings', () => {
  1327. it('can parse decorators syntax in typescript block', () => {
  1328. const { scriptAst } = compile(`
  1329. <script lang="ts">
  1330. import { Options, Vue } from 'vue-class-component';
  1331. @Options({
  1332. components: {
  1333. HelloWorld,
  1334. },
  1335. props: ['foo', 'bar']
  1336. })
  1337. export default class Home extends Vue {}
  1338. </script>
  1339. `)
  1340. expect(scriptAst).toBeDefined()
  1341. })
  1342. it('recognizes props array declaration', () => {
  1343. const { bindings } = compile(`
  1344. <script>
  1345. export default {
  1346. props: ['foo', 'bar']
  1347. }
  1348. </script>
  1349. `)
  1350. expect(bindings).toStrictEqual({
  1351. foo: BindingTypes.PROPS,
  1352. bar: BindingTypes.PROPS
  1353. })
  1354. expect(bindings!.__isScriptSetup).toBe(false)
  1355. })
  1356. it('recognizes props object declaration', () => {
  1357. const { bindings } = compile(`
  1358. <script>
  1359. export default {
  1360. props: {
  1361. foo: String,
  1362. bar: {
  1363. type: String,
  1364. },
  1365. baz: null,
  1366. qux: [String, Number]
  1367. }
  1368. }
  1369. </script>
  1370. `)
  1371. expect(bindings).toStrictEqual({
  1372. foo: BindingTypes.PROPS,
  1373. bar: BindingTypes.PROPS,
  1374. baz: BindingTypes.PROPS,
  1375. qux: BindingTypes.PROPS
  1376. })
  1377. expect(bindings!.__isScriptSetup).toBe(false)
  1378. })
  1379. it('recognizes setup return', () => {
  1380. const { bindings } = compile(`
  1381. <script>
  1382. const bar = 2
  1383. export default {
  1384. setup() {
  1385. return {
  1386. foo: 1,
  1387. bar
  1388. }
  1389. }
  1390. }
  1391. </script>
  1392. `)
  1393. expect(bindings).toStrictEqual({
  1394. foo: BindingTypes.SETUP_MAYBE_REF,
  1395. bar: BindingTypes.SETUP_MAYBE_REF
  1396. })
  1397. expect(bindings!.__isScriptSetup).toBe(false)
  1398. })
  1399. it('recognizes exported vars', () => {
  1400. const { bindings } = compile(`
  1401. <script>
  1402. export const foo = 2
  1403. </script>
  1404. <script setup>
  1405. console.log(foo)
  1406. </script>
  1407. `)
  1408. expect(bindings).toStrictEqual({
  1409. foo: BindingTypes.SETUP_CONST
  1410. })
  1411. })
  1412. it('recognizes async setup return', () => {
  1413. const { bindings } = compile(`
  1414. <script>
  1415. const bar = 2
  1416. export default {
  1417. async setup() {
  1418. return {
  1419. foo: 1,
  1420. bar
  1421. }
  1422. }
  1423. }
  1424. </script>
  1425. `)
  1426. expect(bindings).toStrictEqual({
  1427. foo: BindingTypes.SETUP_MAYBE_REF,
  1428. bar: BindingTypes.SETUP_MAYBE_REF
  1429. })
  1430. expect(bindings!.__isScriptSetup).toBe(false)
  1431. })
  1432. it('recognizes data return', () => {
  1433. const { bindings } = compile(`
  1434. <script>
  1435. const bar = 2
  1436. export default {
  1437. data() {
  1438. return {
  1439. foo: null,
  1440. bar
  1441. }
  1442. }
  1443. }
  1444. </script>
  1445. `)
  1446. expect(bindings).toStrictEqual({
  1447. foo: BindingTypes.DATA,
  1448. bar: BindingTypes.DATA
  1449. })
  1450. })
  1451. it('recognizes methods', () => {
  1452. const { bindings } = compile(`
  1453. <script>
  1454. export default {
  1455. methods: {
  1456. foo() {}
  1457. }
  1458. }
  1459. </script>
  1460. `)
  1461. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1462. })
  1463. it('recognizes computeds', () => {
  1464. const { bindings } = compile(`
  1465. <script>
  1466. export default {
  1467. computed: {
  1468. foo() {},
  1469. bar: {
  1470. get() {},
  1471. set() {},
  1472. }
  1473. }
  1474. }
  1475. </script>
  1476. `)
  1477. expect(bindings).toStrictEqual({
  1478. foo: BindingTypes.OPTIONS,
  1479. bar: BindingTypes.OPTIONS
  1480. })
  1481. })
  1482. it('recognizes injections array declaration', () => {
  1483. const { bindings } = compile(`
  1484. <script>
  1485. export default {
  1486. inject: ['foo', 'bar']
  1487. }
  1488. </script>
  1489. `)
  1490. expect(bindings).toStrictEqual({
  1491. foo: BindingTypes.OPTIONS,
  1492. bar: BindingTypes.OPTIONS
  1493. })
  1494. })
  1495. it('recognizes injections object declaration', () => {
  1496. const { bindings } = compile(`
  1497. <script>
  1498. export default {
  1499. inject: {
  1500. foo: {},
  1501. bar: {},
  1502. }
  1503. }
  1504. </script>
  1505. `)
  1506. expect(bindings).toStrictEqual({
  1507. foo: BindingTypes.OPTIONS,
  1508. bar: BindingTypes.OPTIONS
  1509. })
  1510. })
  1511. it('works for mixed bindings', () => {
  1512. const { bindings } = compile(`
  1513. <script>
  1514. export default {
  1515. inject: ['foo'],
  1516. props: {
  1517. bar: String,
  1518. },
  1519. setup() {
  1520. return {
  1521. baz: null,
  1522. }
  1523. },
  1524. data() {
  1525. return {
  1526. qux: null
  1527. }
  1528. },
  1529. methods: {
  1530. quux() {}
  1531. },
  1532. computed: {
  1533. quuz() {}
  1534. }
  1535. }
  1536. </script>
  1537. `)
  1538. expect(bindings).toStrictEqual({
  1539. foo: BindingTypes.OPTIONS,
  1540. bar: BindingTypes.PROPS,
  1541. baz: BindingTypes.SETUP_MAYBE_REF,
  1542. qux: BindingTypes.DATA,
  1543. quux: BindingTypes.OPTIONS,
  1544. quuz: BindingTypes.OPTIONS
  1545. })
  1546. })
  1547. it('works for script setup', () => {
  1548. const { bindings } = compile(`
  1549. <script setup>
  1550. import { ref as r } from 'vue'
  1551. defineProps({
  1552. foo: String
  1553. })
  1554. const a = r(1)
  1555. let b = 2
  1556. const c = 3
  1557. const { d } = someFoo()
  1558. let { e } = someBar()
  1559. </script>
  1560. `)
  1561. expect(bindings).toStrictEqual({
  1562. r: BindingTypes.SETUP_CONST,
  1563. a: BindingTypes.SETUP_REF,
  1564. b: BindingTypes.SETUP_LET,
  1565. c: BindingTypes.SETUP_CONST,
  1566. d: BindingTypes.SETUP_MAYBE_REF,
  1567. e: BindingTypes.SETUP_LET,
  1568. foo: BindingTypes.PROPS
  1569. })
  1570. })
  1571. describe('auto name inference', () => {
  1572. test('basic', () => {
  1573. const { content } = compile(
  1574. `<script setup>const a = 1</script>
  1575. <template>{{ a }}</template>`,
  1576. undefined,
  1577. {
  1578. filename: 'FooBar.vue'
  1579. }
  1580. )
  1581. expect(content).toMatch(`export default {
  1582. __name: 'FooBar'`)
  1583. assertCode(content)
  1584. })
  1585. test('do not overwrite manual name (object)', () => {
  1586. const { content } = compile(
  1587. `<script>
  1588. export default {
  1589. name: 'Baz'
  1590. }
  1591. </script>
  1592. <script setup>const a = 1</script>
  1593. <template>{{ a }}</template>`,
  1594. undefined,
  1595. {
  1596. filename: 'FooBar.vue'
  1597. }
  1598. )
  1599. expect(content).not.toMatch(`name: 'FooBar'`)
  1600. expect(content).toMatch(`name: 'Baz'`)
  1601. assertCode(content)
  1602. })
  1603. test('do not overwrite manual name (call)', () => {
  1604. const { content } = compile(
  1605. `<script>
  1606. import { defineComponent } from 'vue'
  1607. export default defineComponent({
  1608. name: 'Baz'
  1609. })
  1610. </script>
  1611. <script setup>const a = 1</script>
  1612. <template>{{ a }}</template>`,
  1613. undefined,
  1614. {
  1615. filename: 'FooBar.vue'
  1616. }
  1617. )
  1618. expect(content).not.toMatch(`name: 'FooBar'`)
  1619. expect(content).toMatch(`name: 'Baz'`)
  1620. assertCode(content)
  1621. })
  1622. })
  1623. })