compileScript.spec.ts 37 KB

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