compileScript.spec.ts 48 KB

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