compileScript.spec.ts 56 KB

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