compileScript.spec.ts 53 KB

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