compileScript.spec.ts 34 KB

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