compileScript.spec.ts 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. import { BindingTypes } from '../src/types'
  2. import { parse, ParseOptions } from '../src/parse'
  3. import { parse as babelParse } from '@babel/parser'
  4. import { compileScript, ScriptCompileOptions } from '../src/compileScript'
  5. function compile(
  6. source: string,
  7. options?: Partial<ScriptCompileOptions>,
  8. parseOptions?: Partial<ParseOptions>
  9. ) {
  10. const sfc = parse({
  11. ...parseOptions,
  12. source
  13. })
  14. return compileScript(sfc, options)
  15. }
  16. function assertCode(code: string) {
  17. // parse the generated code to make sure it is valid
  18. try {
  19. babelParse(code, {
  20. sourceType: 'module',
  21. plugins: ['typescript']
  22. })
  23. } catch (e: any) {
  24. console.log(code)
  25. throw e
  26. }
  27. expect(code).toMatchSnapshot()
  28. }
  29. describe('SFC compile <script setup>', () => {
  30. test('should expose top level declarations', () => {
  31. const { content, bindings } = compile(`
  32. <script setup>
  33. import { x } from './x'
  34. let a = 1
  35. const b = 2
  36. function c() {}
  37. class d {}
  38. </script>
  39. <script>
  40. import { xx } from './x'
  41. let aa = 1
  42. const bb = 2
  43. function cc() {}
  44. class dd {}
  45. </script>
  46. `)
  47. expect(content).toMatch('return { aa, bb, cc, dd, a, b, c, d, xx, x }')
  48. expect(bindings).toStrictEqual({
  49. x: BindingTypes.SETUP_MAYBE_REF,
  50. a: BindingTypes.SETUP_LET,
  51. b: BindingTypes.SETUP_CONST,
  52. c: BindingTypes.SETUP_CONST,
  53. d: BindingTypes.SETUP_CONST,
  54. xx: BindingTypes.SETUP_MAYBE_REF,
  55. aa: BindingTypes.SETUP_LET,
  56. bb: BindingTypes.SETUP_CONST,
  57. cc: BindingTypes.SETUP_CONST,
  58. dd: BindingTypes.SETUP_CONST
  59. })
  60. assertCode(content)
  61. })
  62. test('binding analysis for destructure', () => {
  63. const { content, bindings } = compile(`
  64. <script setup>
  65. const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {}
  66. </script>
  67. `)
  68. expect(content).toMatch('return { foo, bar, baz, y, z }')
  69. expect(bindings).toStrictEqual({
  70. foo: BindingTypes.SETUP_MAYBE_REF,
  71. bar: BindingTypes.SETUP_MAYBE_REF,
  72. baz: BindingTypes.SETUP_MAYBE_REF,
  73. y: BindingTypes.SETUP_MAYBE_REF,
  74. z: BindingTypes.SETUP_MAYBE_REF
  75. })
  76. assertCode(content)
  77. })
  78. test('defineProps()', () => {
  79. const { content, bindings } = compile(`
  80. <script setup>
  81. const props = defineProps({
  82. foo: String
  83. })
  84. const bar = 1
  85. </script>
  86. `)
  87. // should generate working code
  88. assertCode(content)
  89. // should analyze bindings
  90. expect(bindings).toStrictEqual({
  91. foo: BindingTypes.PROPS,
  92. bar: BindingTypes.SETUP_CONST,
  93. props: BindingTypes.SETUP_REACTIVE_CONST
  94. })
  95. // should remove defineOptions import and call
  96. expect(content).not.toMatch('defineProps')
  97. // should generate correct setup signature
  98. expect(content).toMatch(`setup(__props) {`)
  99. // should assign user identifier to it
  100. expect(content).toMatch(`const props = __props`)
  101. // should include context options in default export
  102. expect(content).toMatch(`export default {
  103. props: {
  104. foo: String
  105. },`)
  106. })
  107. test('defineProps w/ external definition', () => {
  108. const { content } = compile(`
  109. <script setup>
  110. import { propsModel } from './props'
  111. const props = defineProps(propsModel)
  112. </script>
  113. `)
  114. assertCode(content)
  115. expect(content).toMatch(`export default {
  116. props: propsModel,`)
  117. })
  118. // #4764
  119. test('defineProps w/ leading code', () => {
  120. const { content } = compile(`
  121. <script setup>import { x } from './x'
  122. const props = defineProps({})
  123. </script>
  124. `)
  125. // props declaration should be inside setup, not moved along with the import
  126. expect(content).not.toMatch(`const props = __props\nimport`)
  127. assertCode(content)
  128. })
  129. test('defineEmits()', () => {
  130. const { content, bindings } = compile(`
  131. <script setup>
  132. const myEmit = defineEmits(['foo', 'bar'])
  133. </script>
  134. `)
  135. assertCode(content)
  136. expect(bindings).toStrictEqual({
  137. myEmit: BindingTypes.SETUP_CONST
  138. })
  139. // should remove defineOptions import and call
  140. expect(content).not.toMatch('defineEmits')
  141. // should generate correct setup signature
  142. expect(content).toMatch(`setup(__props, { emit: myEmit }) {`)
  143. // should include context options in default export
  144. expect(content).toMatch(`export default {
  145. emits: ['foo', 'bar'],`)
  146. })
  147. test('defineProps/defineEmits in multi-variable declaration', () => {
  148. const { content } = compile(`
  149. <script setup>
  150. const props = defineProps(['item']),
  151. a = 1,
  152. emit = defineEmits(['a']);
  153. </script>
  154. `)
  155. assertCode(content)
  156. expect(content).toMatch(`const a = 1;`) // test correct removal
  157. expect(content).toMatch(`props: ['item'],`)
  158. expect(content).toMatch(`emits: ['a'],`)
  159. })
  160. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  161. const { content } = compile(`
  162. <script setup>
  163. const props = defineProps(['item']),
  164. emit = defineEmits(['a']);
  165. </script>
  166. `)
  167. assertCode(content)
  168. expect(content).toMatch(`props: ['item'],`)
  169. expect(content).toMatch(`emits: ['a'],`)
  170. })
  171. test('defineExpose()', () => {
  172. const { content } = compile(`
  173. <script setup>
  174. defineExpose({ foo: 123 })
  175. </script>
  176. `)
  177. assertCode(content)
  178. // should remove defineOptions import and call
  179. expect(content).not.toMatch('defineExpose')
  180. // should generate correct setup signature
  181. expect(content).toMatch(`setup(__props, { expose }) {`)
  182. // should replace callee
  183. expect(content).toMatch(/\bexpose\(\{ foo: 123 \}\)/)
  184. })
  185. test('<script> after <script setup> the script content not end with `\\n`', () => {
  186. const { content } = compile(`
  187. <script setup>
  188. import { x } from './x'
  189. </script>
  190. <script>const n = 1</script>
  191. `)
  192. assertCode(content)
  193. })
  194. describe('<script> and <script setup> co-usage', () => {
  195. test('script first', () => {
  196. const { content } = compile(`
  197. <script>
  198. export const n = 1
  199. export default {}
  200. </script>
  201. <script setup>
  202. import { x } from './x'
  203. x()
  204. </script>
  205. `)
  206. assertCode(content)
  207. })
  208. test('script setup first', () => {
  209. const { content } = compile(`
  210. <script setup>
  211. import { x } from './x'
  212. x()
  213. </script>
  214. <script>
  215. export const n = 1
  216. export default {}
  217. </script>
  218. `)
  219. assertCode(content)
  220. })
  221. test('script setup first, named default export', () => {
  222. const { content } = compile(`
  223. <script setup>
  224. import { x } from './x'
  225. x()
  226. </script>
  227. <script>
  228. export const n = 1
  229. const def = {}
  230. export { def as default }
  231. </script>
  232. `)
  233. assertCode(content)
  234. })
  235. // #4395
  236. test('script setup first, lang="ts", script block content export default', () => {
  237. const { content } = compile(`
  238. <script setup lang="ts">
  239. import { x } from './x'
  240. x()
  241. </script>
  242. <script lang="ts">
  243. export default {
  244. name: "test"
  245. }
  246. </script>
  247. `)
  248. // ensure __default__ is declared before used
  249. expect(content).toMatch(/const __default__[\S\s]*\.\.\.__default__/m)
  250. assertCode(content)
  251. })
  252. describe('spaces in ExportDefaultDeclaration node', () => {
  253. // #4371
  254. test('with many spaces and newline', () => {
  255. // #4371
  256. const { content } = compile(`
  257. <script>
  258. export const n = 1
  259. export default
  260. {
  261. some:'option'
  262. }
  263. </script>
  264. <script setup>
  265. import { x } from './x'
  266. x()
  267. </script>
  268. `)
  269. assertCode(content)
  270. })
  271. test('with minimal spaces', () => {
  272. const { content } = compile(`
  273. <script>
  274. export const n = 1
  275. export default{
  276. some:'option'
  277. }
  278. </script>
  279. <script setup>
  280. import { x } from './x'
  281. x()
  282. </script>
  283. `)
  284. assertCode(content)
  285. })
  286. })
  287. })
  288. describe('imports', () => {
  289. test('should hoist and expose imports', () => {
  290. assertCode(
  291. compile(`<script setup>
  292. import { ref } from 'vue'
  293. import 'foo/css'
  294. </script>`).content
  295. )
  296. })
  297. test('should extract comment for import or type declarations', () => {
  298. assertCode(
  299. compile(`
  300. <script setup>
  301. import a from 'a' // comment
  302. import b from 'b'
  303. </script>
  304. `).content
  305. )
  306. })
  307. // #2740
  308. test('should allow defineProps/Emit at the start of imports', () => {
  309. assertCode(
  310. compile(`<script setup>
  311. import { ref } from 'vue'
  312. defineProps(['foo'])
  313. defineEmits(['bar'])
  314. const r = ref(0)
  315. </script>`).content
  316. )
  317. })
  318. test('import dedupe between <script> and <script setup>', () => {
  319. const { content } = compile(`
  320. <script>
  321. import { x } from './x'
  322. </script>
  323. <script setup>
  324. import { x } from './x'
  325. x()
  326. </script>
  327. `)
  328. assertCode(content)
  329. expect(content.indexOf(`import { x }`)).toEqual(
  330. content.lastIndexOf(`import { x }`)
  331. )
  332. })
  333. })
  334. // in dev mode, declared bindings are returned as an object from setup()
  335. // when using TS, users may import types which should not be returned as
  336. // values, so we need to check import usage in the template to determine
  337. // what to be returned.
  338. describe('dev mode import usage check', () => {
  339. test('components', () => {
  340. const { content } = compile(`
  341. <script setup lang="ts">
  342. import { FooBar, FooBaz, FooQux, foo } from './x'
  343. const fooBar: FooBar = 1
  344. </script>
  345. <template>
  346. <FooBaz></FooBaz>
  347. <foo-qux/>
  348. <foo/>
  349. FooBar
  350. </template>
  351. `)
  352. // FooBar: should not be matched by plain text or incorrect case
  353. // FooBaz: used as PascalCase component
  354. // FooQux: used as kebab-case component
  355. // foo: lowercase component
  356. expect(content).toMatch(`return { fooBar, FooBaz, FooQux, foo }`)
  357. assertCode(content)
  358. })
  359. test('directive', () => {
  360. const { content } = compile(`
  361. <script setup lang="ts">
  362. import { vMyDir } from './x'
  363. </script>
  364. <template>
  365. <div v-my-dir></div>
  366. </template>
  367. `)
  368. expect(content).toMatch(`return { vMyDir }`)
  369. assertCode(content)
  370. })
  371. // https://github.com/vuejs/core/issues/4599
  372. test('attribute expressions', () => {
  373. const { content } = compile(`
  374. <script setup lang="ts">
  375. import { bar, baz } from './x'
  376. const cond = true
  377. </script>
  378. <template>
  379. <div :class="[cond ? '' : bar(), 'default']" :style="baz"></div>
  380. </template>
  381. `)
  382. expect(content).toMatch(`return { cond, bar, baz }`)
  383. assertCode(content)
  384. })
  385. test('vue interpolations', () => {
  386. const { content } = compile(`
  387. <script setup lang="ts">
  388. import { x, y, z, x$y } from './x'
  389. </script>
  390. <template>
  391. <div :id="z + 'y'">{{ x }} {{ yy }} {{ x$y }}</div>
  392. </template>
  393. `)
  394. // x: used in interpolation
  395. // y: should not be matched by {{ yy }} or 'y' in binding exps
  396. // x$y: #4274 should escape special chars when creating Regex
  397. expect(content).toMatch(`return { x, z, x$y }`)
  398. assertCode(content)
  399. })
  400. // #4340 interpolations in template strings
  401. test('js template string interpolations', () => {
  402. const { content } = compile(`
  403. <script setup lang="ts">
  404. import { VAR, VAR2, VAR3 } from './x'
  405. </script>
  406. <template>
  407. {{ \`\${VAR}VAR2\${VAR3}\` }}
  408. </template>
  409. `)
  410. // VAR2 should not be matched
  411. expect(content).toMatch(`return { VAR, VAR3 }`)
  412. assertCode(content)
  413. })
  414. // edge case: last tag in template
  415. test('last tag', () => {
  416. const { content } = compile(`
  417. <script setup lang="ts">
  418. import { FooBaz, Last } from './x'
  419. </script>
  420. <template>
  421. <FooBaz></FooBaz>
  422. <Last/>
  423. </template>
  424. `)
  425. expect(content).toMatch(`return { FooBaz, Last }`)
  426. assertCode(content)
  427. })
  428. test('TS annotations', () => {
  429. const { content } = compile(`
  430. <script setup lang="ts">
  431. import { Foo, Baz, Qux, Fred } from './x'
  432. const a = 1
  433. function b() {}
  434. </script>
  435. <template>
  436. {{ a as Foo }}
  437. {{ Baz }}
  438. <Comp v-slot="{ data }: Qux">{{ data }}</Comp>
  439. <div v-for="{ z = x as Qux } in list as Fred"/>
  440. </template>
  441. `)
  442. expect(content).toMatch(`return { a, b, Baz }`)
  443. assertCode(content)
  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, { 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/ exported interface', () => {
  840. const { content, bindings } = compile(`
  841. <script setup lang="ts">
  842. export interface Props { x?: number }
  843. defineProps<Props>()
  844. </script>
  845. `)
  846. assertCode(content)
  847. expect(content).toMatch(`x: { type: Number, required: false }`)
  848. expect(bindings).toStrictEqual({
  849. x: BindingTypes.PROPS
  850. })
  851. })
  852. test('defineProps w/ exported interface in normal script', () => {
  853. const { content, bindings } = compile(`
  854. <script lang="ts">
  855. export interface Props { x?: number }
  856. </script>
  857. <script setup lang="ts">
  858. defineProps<Props>()
  859. </script>
  860. `)
  861. assertCode(content)
  862. expect(content).toMatch(`x: { type: Number, required: false }`)
  863. expect(bindings).toStrictEqual({
  864. x: BindingTypes.PROPS
  865. })
  866. })
  867. test('defineProps w/ type alias', () => {
  868. const { content, bindings } = compile(`
  869. <script setup lang="ts">
  870. type Props = { x?: number }
  871. defineProps<Props>()
  872. </script>
  873. `)
  874. assertCode(content)
  875. expect(content).toMatch(`x: { type: Number, required: false }`)
  876. expect(bindings).toStrictEqual({
  877. x: BindingTypes.PROPS
  878. })
  879. })
  880. test('defineProps w/ exported type alias', () => {
  881. const { content, bindings } = compile(`
  882. <script setup lang="ts">
  883. export type Props = { x?: number }
  884. defineProps<Props>()
  885. </script>
  886. `)
  887. assertCode(content)
  888. expect(content).toMatch(`x: { type: Number, required: false }`)
  889. expect(bindings).toStrictEqual({
  890. x: BindingTypes.PROPS
  891. })
  892. })
  893. test('withDefaults (static)', () => {
  894. const { content, bindings } = compile(`
  895. <script setup lang="ts">
  896. const props = withDefaults(defineProps<{
  897. foo?: string
  898. bar?: number;
  899. baz: boolean;
  900. qux?(): number
  901. }>(), {
  902. foo: 'hi',
  903. qux() { return 1 }
  904. })
  905. </script>
  906. `)
  907. assertCode(content)
  908. expect(content).toMatch(
  909. `foo: { type: String, required: false, default: 'hi' }`
  910. )
  911. expect(content).toMatch(`bar: { type: Number, required: false }`)
  912. expect(content).toMatch(`baz: { type: Boolean, required: true }`)
  913. expect(content).toMatch(
  914. `qux: { type: Function, required: false, default() { return 1 } }`
  915. )
  916. expect(content).toMatch(
  917. `{ foo: string, bar?: number, baz: boolean, qux(): number }`
  918. )
  919. expect(content).toMatch(`const props = __props`)
  920. expect(bindings).toStrictEqual({
  921. foo: BindingTypes.PROPS,
  922. bar: BindingTypes.PROPS,
  923. baz: BindingTypes.PROPS,
  924. qux: BindingTypes.PROPS,
  925. props: BindingTypes.SETUP_CONST
  926. })
  927. })
  928. test('withDefaults (dynamic)', () => {
  929. const { content } = compile(`
  930. <script setup lang="ts">
  931. import { defaults } from './foo'
  932. const props = withDefaults(defineProps<{
  933. foo?: string
  934. bar?: number
  935. baz: boolean
  936. }>(), { ...defaults })
  937. </script>
  938. `)
  939. assertCode(content)
  940. expect(content).toMatch(`import { mergeDefaults as _mergeDefaults`)
  941. expect(content).toMatch(
  942. `
  943. _mergeDefaults({
  944. foo: { type: String, required: false },
  945. bar: { type: Number, required: false },
  946. baz: { type: Boolean, required: true }
  947. }, { ...defaults })`.trim()
  948. )
  949. })
  950. test('defineEmits w/ type', () => {
  951. const { content } = compile(`
  952. <script setup lang="ts">
  953. const emit = defineEmits<(e: 'foo' | 'bar') => void>()
  954. </script>
  955. `)
  956. assertCode(content)
  957. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  958. expect(content).toMatch(`emits: ["foo", "bar"]`)
  959. })
  960. test('defineEmits w/ type (union)', () => {
  961. const type = `((e: 'foo' | 'bar') => void) | ((e: 'baz', id: number) => void)`
  962. expect(() =>
  963. compile(`
  964. <script setup lang="ts">
  965. const emit = defineEmits<${type}>()
  966. </script>
  967. `)
  968. ).toThrow()
  969. })
  970. test('defineEmits w/ type (type literal w/ call signatures)', () => {
  971. const type = `{(e: 'foo' | 'bar'): void; (e: 'baz', id: number): void;}`
  972. const { content } = compile(`
  973. <script setup lang="ts">
  974. const emit = defineEmits<${type}>()
  975. </script>
  976. `)
  977. assertCode(content)
  978. expect(content).toMatch(`emit: (${type}),`)
  979. expect(content).toMatch(`emits: ["foo", "bar", "baz"]`)
  980. })
  981. test('defineEmits w/ type (interface)', () => {
  982. const { content } = compile(`
  983. <script setup lang="ts">
  984. interface Emits { (e: 'foo' | 'bar'): void }
  985. const emit = defineEmits<Emits>()
  986. </script>
  987. `)
  988. assertCode(content)
  989. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  990. expect(content).toMatch(`emits: ["foo", "bar"]`)
  991. })
  992. test('defineEmits w/ type (exported interface)', () => {
  993. const { content } = compile(`
  994. <script setup lang="ts">
  995. export interface Emits { (e: 'foo' | 'bar'): void }
  996. const emit = defineEmits<Emits>()
  997. </script>
  998. `)
  999. assertCode(content)
  1000. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1001. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1002. })
  1003. test('defineEmits w/ type (type alias)', () => {
  1004. const { content } = compile(`
  1005. <script setup lang="ts">
  1006. type Emits = { (e: 'foo' | 'bar'): void }
  1007. const emit = defineEmits<Emits>()
  1008. </script>
  1009. `)
  1010. assertCode(content)
  1011. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1012. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1013. })
  1014. test('defineEmits w/ type (exported type alias)', () => {
  1015. const { content } = compile(`
  1016. <script setup lang="ts">
  1017. export type Emits = { (e: 'foo' | 'bar'): void }
  1018. const emit = defineEmits<Emits>()
  1019. </script>
  1020. `)
  1021. assertCode(content)
  1022. expect(content).toMatch(`emit: ({ (e: 'foo' | 'bar'): void }),`)
  1023. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1024. })
  1025. test('defineEmits w/ type (referenced function type)', () => {
  1026. const { content } = compile(`
  1027. <script setup lang="ts">
  1028. type Emits = (e: 'foo' | 'bar') => void
  1029. const emit = defineEmits<Emits>()
  1030. </script>
  1031. `)
  1032. assertCode(content)
  1033. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1034. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1035. })
  1036. test('defineEmits w/ type (referenced exported function type)', () => {
  1037. const { content } = compile(`
  1038. <script setup lang="ts">
  1039. export type Emits = (e: 'foo' | 'bar') => void
  1040. const emit = defineEmits<Emits>()
  1041. </script>
  1042. `)
  1043. assertCode(content)
  1044. expect(content).toMatch(`emit: ((e: 'foo' | 'bar') => void),`)
  1045. expect(content).toMatch(`emits: ["foo", "bar"]`)
  1046. })
  1047. test('runtime Enum', () => {
  1048. const { content, bindings } = compile(
  1049. `<script setup lang="ts">
  1050. enum Foo { A = 123 }
  1051. </script>`
  1052. )
  1053. assertCode(content)
  1054. expect(bindings).toStrictEqual({
  1055. Foo: BindingTypes.SETUP_CONST
  1056. })
  1057. })
  1058. test('runtime Enum in normal script', () => {
  1059. const { content, bindings } = compile(
  1060. `<script lang="ts">
  1061. export enum D { D = "D" }
  1062. const enum C { C = "C" }
  1063. enum B { B = "B" }
  1064. </script>
  1065. <script setup lang="ts">
  1066. enum Foo { A = 123 }
  1067. </script>`
  1068. )
  1069. assertCode(content)
  1070. expect(bindings).toStrictEqual({
  1071. D: BindingTypes.SETUP_CONST,
  1072. C: BindingTypes.SETUP_CONST,
  1073. B: BindingTypes.SETUP_CONST,
  1074. Foo: BindingTypes.SETUP_CONST
  1075. })
  1076. })
  1077. test('const Enum', () => {
  1078. const { content, bindings } = compile(
  1079. `<script setup lang="ts">
  1080. const enum Foo { A = 123 }
  1081. </script>`
  1082. )
  1083. assertCode(content)
  1084. expect(bindings).toStrictEqual({
  1085. Foo: BindingTypes.SETUP_CONST
  1086. })
  1087. })
  1088. test('import type', () => {
  1089. const { content } = compile(
  1090. `<script setup lang="ts">
  1091. import type { Foo } from './main.ts'
  1092. import { type Bar, Baz } from './main.ts'
  1093. </script>`
  1094. )
  1095. expect(content).toMatch(`return { Baz }`)
  1096. assertCode(content)
  1097. })
  1098. })
  1099. describe('async/await detection', () => {
  1100. function assertAwaitDetection(code: string, shouldAsync = true) {
  1101. const { content } = compile(`<script setup>${code}</script>`)
  1102. if (shouldAsync) {
  1103. expect(content).toMatch(`let __temp, __restore`)
  1104. }
  1105. expect(content).toMatch(`${shouldAsync ? `async ` : ``}setup(`)
  1106. assertCode(content)
  1107. return content
  1108. }
  1109. test('expression statement', () => {
  1110. assertAwaitDetection(`await foo`)
  1111. })
  1112. test('variable', () => {
  1113. assertAwaitDetection(`const a = 1 + (await foo)`)
  1114. })
  1115. test('ref', () => {
  1116. assertAwaitDetection(`let a = $ref(1 + (await foo))`)
  1117. })
  1118. // #4448
  1119. test('nested await', () => {
  1120. assertAwaitDetection(`await (await foo)`)
  1121. assertAwaitDetection(`await ((await foo))`)
  1122. assertAwaitDetection(`await (await (await foo))`)
  1123. })
  1124. // should prepend semicolon
  1125. test('nested leading await in expression statement', () => {
  1126. const code = assertAwaitDetection(`foo()\nawait 1 + await 2`)
  1127. expect(code).toMatch(`foo()\n;(`)
  1128. })
  1129. // #4596 should NOT prepend semicolon
  1130. test('single line conditions', () => {
  1131. const code = assertAwaitDetection(`if (false) await foo()`)
  1132. expect(code).not.toMatch(`if (false) ;(`)
  1133. })
  1134. test('nested statements', () => {
  1135. assertAwaitDetection(`if (ok) { await foo } else { await bar }`)
  1136. })
  1137. test('multiple `if` nested statements', () => {
  1138. assertAwaitDetection(`if (ok) {
  1139. let a = 'foo'
  1140. await 0 + await 1
  1141. await 2
  1142. } else if (a) {
  1143. await 10
  1144. if (b) {
  1145. await 0 + await 1
  1146. } else {
  1147. let a = 'foo'
  1148. await 2
  1149. }
  1150. if (b) {
  1151. await 3
  1152. await 4
  1153. }
  1154. } else {
  1155. await 5
  1156. }`)
  1157. })
  1158. test('multiple `if while` nested statements', () => {
  1159. assertAwaitDetection(`if (ok) {
  1160. while (d) {
  1161. await 5
  1162. }
  1163. while (d) {
  1164. await 5
  1165. await 6
  1166. if (c) {
  1167. let f = 10
  1168. 10 + await 7
  1169. } else {
  1170. await 8
  1171. await 9
  1172. }
  1173. }
  1174. }`)
  1175. })
  1176. test('multiple `if for` nested statements', () => {
  1177. assertAwaitDetection(`if (ok) {
  1178. for (let a of [1,2,3]) {
  1179. await a
  1180. }
  1181. for (let a of [1,2,3]) {
  1182. await a
  1183. await a
  1184. }
  1185. }`)
  1186. })
  1187. test('should ignore await inside functions', () => {
  1188. // function declaration
  1189. assertAwaitDetection(`async function foo() { await bar }`, false)
  1190. // function expression
  1191. assertAwaitDetection(`const foo = async () => { await bar }`, false)
  1192. // object method
  1193. assertAwaitDetection(`const obj = { async method() { await bar }}`, false)
  1194. // class method
  1195. assertAwaitDetection(
  1196. `const cls = class Foo { async method() { await bar }}`,
  1197. false
  1198. )
  1199. })
  1200. })
  1201. describe('errors', () => {
  1202. test('<script> and <script setup> must have same lang', () => {
  1203. expect(() =>
  1204. compile(`<script>foo()</script><script setup lang="ts">bar()</script>`)
  1205. ).toThrow(`<script> and <script setup> must have the same language type`)
  1206. })
  1207. const moduleErrorMsg = `cannot contain ES module exports`
  1208. test('non-type named exports', () => {
  1209. expect(() =>
  1210. compile(`<script setup>
  1211. export const a = 1
  1212. </script>`)
  1213. ).toThrow(moduleErrorMsg)
  1214. expect(() =>
  1215. compile(`<script setup>
  1216. export * from './foo'
  1217. </script>`)
  1218. ).toThrow(moduleErrorMsg)
  1219. expect(() =>
  1220. compile(`<script setup>
  1221. const bar = 1
  1222. export { bar as default }
  1223. </script>`)
  1224. ).toThrow(moduleErrorMsg)
  1225. })
  1226. test('defineProps/Emit() w/ both type and non-type args', () => {
  1227. expect(() => {
  1228. compile(`<script setup lang="ts">
  1229. defineProps<{}>({})
  1230. </script>`)
  1231. }).toThrow(`cannot accept both type and non-type arguments`)
  1232. expect(() => {
  1233. compile(`<script setup lang="ts">
  1234. defineEmits<{}>({})
  1235. </script>`)
  1236. }).toThrow(`cannot accept both type and non-type arguments`)
  1237. })
  1238. test('defineProps/Emit() referencing local var', () => {
  1239. expect(() =>
  1240. compile(`<script setup>
  1241. const bar = 1
  1242. defineProps({
  1243. foo: {
  1244. default: () => bar
  1245. }
  1246. })
  1247. </script>`)
  1248. ).toThrow(`cannot reference locally declared variables`)
  1249. expect(() =>
  1250. compile(`<script setup>
  1251. const bar = 'hello'
  1252. defineEmits([bar])
  1253. </script>`)
  1254. ).toThrow(`cannot reference locally declared variables`)
  1255. // #4644
  1256. expect(() =>
  1257. compile(`
  1258. <script>const bar = 1</script>
  1259. <script setup>
  1260. defineProps({
  1261. foo: {
  1262. default: () => bar
  1263. }
  1264. })
  1265. </script>`)
  1266. ).not.toThrow(`cannot reference locally declared variables`)
  1267. })
  1268. test('should allow defineProps/Emit() referencing scope var', () => {
  1269. assertCode(
  1270. compile(`<script setup>
  1271. const bar = 1
  1272. defineProps({
  1273. foo: {
  1274. default: bar => bar + 1
  1275. }
  1276. })
  1277. defineEmits({
  1278. foo: bar => bar > 1
  1279. })
  1280. </script>`).content
  1281. )
  1282. })
  1283. test('should allow defineProps/Emit() referencing imported binding', () => {
  1284. assertCode(
  1285. compile(`<script setup>
  1286. import { bar } from './bar'
  1287. defineProps({
  1288. foo: {
  1289. default: () => bar
  1290. }
  1291. })
  1292. defineEmits({
  1293. foo: () => bar > 1
  1294. })
  1295. </script>`).content
  1296. )
  1297. })
  1298. })
  1299. })
  1300. describe('SFC analyze <script> bindings', () => {
  1301. it('can parse decorators syntax in typescript block', () => {
  1302. const { scriptAst } = compile(`
  1303. <script lang="ts">
  1304. import { Options, Vue } from 'vue-class-component';
  1305. @Options({
  1306. components: {
  1307. HelloWorld,
  1308. },
  1309. props: ['foo', 'bar']
  1310. })
  1311. export default class Home extends Vue {}
  1312. </script>
  1313. `)
  1314. expect(scriptAst).toBeDefined()
  1315. })
  1316. it('recognizes props array declaration', () => {
  1317. const { bindings } = compile(`
  1318. <script>
  1319. export default {
  1320. props: ['foo', 'bar']
  1321. }
  1322. </script>
  1323. `)
  1324. expect(bindings).toStrictEqual({
  1325. foo: BindingTypes.PROPS,
  1326. bar: BindingTypes.PROPS
  1327. })
  1328. expect(bindings!.__isScriptSetup).toBe(false)
  1329. })
  1330. it('recognizes props object declaration', () => {
  1331. const { bindings } = compile(`
  1332. <script>
  1333. export default {
  1334. props: {
  1335. foo: String,
  1336. bar: {
  1337. type: String,
  1338. },
  1339. baz: null,
  1340. qux: [String, Number]
  1341. }
  1342. }
  1343. </script>
  1344. `)
  1345. expect(bindings).toStrictEqual({
  1346. foo: BindingTypes.PROPS,
  1347. bar: BindingTypes.PROPS,
  1348. baz: BindingTypes.PROPS,
  1349. qux: BindingTypes.PROPS
  1350. })
  1351. expect(bindings!.__isScriptSetup).toBe(false)
  1352. })
  1353. it('recognizes setup return', () => {
  1354. const { bindings } = compile(`
  1355. <script>
  1356. const bar = 2
  1357. export default {
  1358. setup() {
  1359. return {
  1360. foo: 1,
  1361. bar
  1362. }
  1363. }
  1364. }
  1365. </script>
  1366. `)
  1367. expect(bindings).toStrictEqual({
  1368. foo: BindingTypes.SETUP_MAYBE_REF,
  1369. bar: BindingTypes.SETUP_MAYBE_REF
  1370. })
  1371. expect(bindings!.__isScriptSetup).toBe(false)
  1372. })
  1373. it('recognizes exported vars', () => {
  1374. const { bindings } = compile(`
  1375. <script>
  1376. export const foo = 2
  1377. </script>
  1378. <script setup>
  1379. console.log(foo)
  1380. </script>
  1381. `)
  1382. expect(bindings).toStrictEqual({
  1383. foo: BindingTypes.SETUP_CONST
  1384. })
  1385. })
  1386. it('recognizes async setup return', () => {
  1387. const { bindings } = compile(`
  1388. <script>
  1389. const bar = 2
  1390. export default {
  1391. async setup() {
  1392. return {
  1393. foo: 1,
  1394. bar
  1395. }
  1396. }
  1397. }
  1398. </script>
  1399. `)
  1400. expect(bindings).toStrictEqual({
  1401. foo: BindingTypes.SETUP_MAYBE_REF,
  1402. bar: BindingTypes.SETUP_MAYBE_REF
  1403. })
  1404. expect(bindings!.__isScriptSetup).toBe(false)
  1405. })
  1406. it('recognizes data return', () => {
  1407. const { bindings } = compile(`
  1408. <script>
  1409. const bar = 2
  1410. export default {
  1411. data() {
  1412. return {
  1413. foo: null,
  1414. bar
  1415. }
  1416. }
  1417. }
  1418. </script>
  1419. `)
  1420. expect(bindings).toStrictEqual({
  1421. foo: BindingTypes.DATA,
  1422. bar: BindingTypes.DATA
  1423. })
  1424. })
  1425. it('recognizes methods', () => {
  1426. const { bindings } = compile(`
  1427. <script>
  1428. export default {
  1429. methods: {
  1430. foo() {}
  1431. }
  1432. }
  1433. </script>
  1434. `)
  1435. expect(bindings).toStrictEqual({ foo: BindingTypes.OPTIONS })
  1436. })
  1437. it('recognizes computeds', () => {
  1438. const { bindings } = compile(`
  1439. <script>
  1440. export default {
  1441. computed: {
  1442. foo() {},
  1443. bar: {
  1444. get() {},
  1445. set() {},
  1446. }
  1447. }
  1448. }
  1449. </script>
  1450. `)
  1451. expect(bindings).toStrictEqual({
  1452. foo: BindingTypes.OPTIONS,
  1453. bar: BindingTypes.OPTIONS
  1454. })
  1455. })
  1456. it('recognizes injections array declaration', () => {
  1457. const { bindings } = compile(`
  1458. <script>
  1459. export default {
  1460. inject: ['foo', 'bar']
  1461. }
  1462. </script>
  1463. `)
  1464. expect(bindings).toStrictEqual({
  1465. foo: BindingTypes.OPTIONS,
  1466. bar: BindingTypes.OPTIONS
  1467. })
  1468. })
  1469. it('recognizes injections object declaration', () => {
  1470. const { bindings } = compile(`
  1471. <script>
  1472. export default {
  1473. inject: {
  1474. foo: {},
  1475. bar: {},
  1476. }
  1477. }
  1478. </script>
  1479. `)
  1480. expect(bindings).toStrictEqual({
  1481. foo: BindingTypes.OPTIONS,
  1482. bar: BindingTypes.OPTIONS
  1483. })
  1484. })
  1485. it('works for mixed bindings', () => {
  1486. const { bindings } = compile(`
  1487. <script>
  1488. export default {
  1489. inject: ['foo'],
  1490. props: {
  1491. bar: String,
  1492. },
  1493. setup() {
  1494. return {
  1495. baz: null,
  1496. }
  1497. },
  1498. data() {
  1499. return {
  1500. qux: null
  1501. }
  1502. },
  1503. methods: {
  1504. quux() {}
  1505. },
  1506. computed: {
  1507. quuz() {}
  1508. }
  1509. }
  1510. </script>
  1511. `)
  1512. expect(bindings).toStrictEqual({
  1513. foo: BindingTypes.OPTIONS,
  1514. bar: BindingTypes.PROPS,
  1515. baz: BindingTypes.SETUP_MAYBE_REF,
  1516. qux: BindingTypes.DATA,
  1517. quux: BindingTypes.OPTIONS,
  1518. quuz: BindingTypes.OPTIONS
  1519. })
  1520. })
  1521. it('works for script setup', () => {
  1522. const { bindings } = compile(`
  1523. <script setup>
  1524. import { ref as r } from 'vue'
  1525. defineProps({
  1526. foo: String
  1527. })
  1528. const a = r(1)
  1529. let b = 2
  1530. const c = 3
  1531. const { d } = someFoo()
  1532. let { e } = someBar()
  1533. </script>
  1534. `)
  1535. expect(bindings).toStrictEqual({
  1536. r: BindingTypes.SETUP_CONST,
  1537. a: BindingTypes.SETUP_REF,
  1538. b: BindingTypes.SETUP_LET,
  1539. c: BindingTypes.SETUP_CONST,
  1540. d: BindingTypes.SETUP_MAYBE_REF,
  1541. e: BindingTypes.SETUP_LET,
  1542. foo: BindingTypes.PROPS
  1543. })
  1544. })
  1545. describe('auto name inference', () => {
  1546. test('basic', () => {
  1547. const { content } = compile(
  1548. `<script setup>const a = 1</script>
  1549. <template>{{ a }}</template>`,
  1550. undefined,
  1551. {
  1552. filename: 'FooBar.vue'
  1553. }
  1554. )
  1555. expect(content).toMatch(`export default {
  1556. __name: 'FooBar'`)
  1557. assertCode(content)
  1558. })
  1559. test('do not overwrite manual name (object)', () => {
  1560. const { content } = compile(
  1561. `<script>
  1562. export default {
  1563. name: 'Baz'
  1564. }
  1565. </script>
  1566. <script setup>const a = 1</script>
  1567. <template>{{ a }}</template>`,
  1568. undefined,
  1569. {
  1570. filename: 'FooBar.vue'
  1571. }
  1572. )
  1573. expect(content).not.toMatch(`name: 'FooBar'`)
  1574. expect(content).toMatch(`name: 'Baz'`)
  1575. assertCode(content)
  1576. })
  1577. test('do not overwrite manual name (call)', () => {
  1578. const { content } = compile(
  1579. `<script>
  1580. import { defineComponent } from 'vue'
  1581. export default defineComponent({
  1582. name: 'Baz'
  1583. })
  1584. </script>
  1585. <script setup>const a = 1</script>
  1586. <template>{{ a }}</template>`,
  1587. undefined,
  1588. {
  1589. filename: 'FooBar.vue'
  1590. }
  1591. )
  1592. expect(content).not.toMatch(`name: 'FooBar'`)
  1593. expect(content).toMatch(`name: 'Baz'`)
  1594. assertCode(content)
  1595. })
  1596. })
  1597. })