compileScript.spec.ts 39 KB

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