definePropsDestructure.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import { BindingTypes } from '@vue/compiler-core'
  2. import type { SFCScriptCompileOptions } from '../../src'
  3. import { assertCode, compileSFCScript } from '../utils'
  4. describe('sfc reactive props destructure', () => {
  5. function compile(src: string, options?: Partial<SFCScriptCompileOptions>) {
  6. return compileSFCScript(src, {
  7. inlineTemplate: true,
  8. ...options,
  9. })
  10. }
  11. test('basic usage', () => {
  12. const { content, bindings } = compile(`
  13. <script setup>
  14. const { foo } = defineProps(['foo'])
  15. console.log(foo)
  16. </script>
  17. <template>{{ foo }}</template>
  18. `)
  19. expect(content).not.toMatch(`const { foo } =`)
  20. expect(content).toMatch(`console.log(__props.foo)`)
  21. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  22. assertCode(content)
  23. expect(bindings).toStrictEqual({
  24. foo: BindingTypes.PROPS,
  25. })
  26. })
  27. test('multiple variable declarations', () => {
  28. const { content, bindings } = compile(`
  29. <script setup>
  30. const bar = 'fish', { foo } = defineProps(['foo']), hello = 'world'
  31. </script>
  32. <template><div>{{ foo }} {{ hello }} {{ bar }}</div></template>
  33. `)
  34. expect(content).not.toMatch(`const { foo } =`)
  35. expect(content).toMatch(`const bar = 'fish', hello = 'world'`)
  36. expect(content).toMatch(`_toDisplayString(hello)`)
  37. expect(content).toMatch(`_toDisplayString(bar)`)
  38. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  39. assertCode(content)
  40. expect(bindings).toStrictEqual({
  41. foo: BindingTypes.PROPS,
  42. bar: BindingTypes.LITERAL_CONST,
  43. hello: BindingTypes.LITERAL_CONST,
  44. })
  45. })
  46. test('nested scope', () => {
  47. const { content, bindings } = compile(`
  48. <script setup>
  49. const { foo, bar } = defineProps(['foo', 'bar'])
  50. function test(foo) {
  51. console.log(foo)
  52. console.log(bar)
  53. }
  54. </script>
  55. `)
  56. expect(content).not.toMatch(`const { foo, bar } =`)
  57. expect(content).toMatch(`console.log(foo)`)
  58. expect(content).toMatch(`console.log(__props.bar)`)
  59. assertCode(content)
  60. expect(bindings).toStrictEqual({
  61. foo: BindingTypes.PROPS,
  62. bar: BindingTypes.PROPS,
  63. test: BindingTypes.SETUP_CONST,
  64. })
  65. })
  66. test('default values w/ array runtime declaration', () => {
  67. const { content } = compile(`
  68. <script setup>
  69. const { foo = 1, bar = {}, func = () => {} } = defineProps(['foo', 'bar', 'baz'])
  70. </script>
  71. `)
  72. // literals can be used as-is, non-literals are always returned from a
  73. // function
  74. // functions need to be marked with a skip marker
  75. expect(content)
  76. .toMatch(`props: /*@__PURE__*/_mergeDefaults(['foo', 'bar', 'baz'], {
  77. foo: 1,
  78. bar: () => ({}),
  79. func: () => {}, __skip_func: true
  80. })`)
  81. assertCode(content)
  82. })
  83. test('default values w/ object runtime declaration', () => {
  84. const { content } = compile(`
  85. <script setup>
  86. const { foo = 1, bar = {}, func = () => {}, ext = x } = defineProps({ foo: Number, bar: Object, func: Function, ext: null })
  87. </script>
  88. `)
  89. // literals can be used as-is, non-literals are always returned from a
  90. // function
  91. // functions need to be marked with a skip marker since we cannot always
  92. // safely infer whether runtime type is Function (e.g. if the runtime decl
  93. // is imported, or spreads another object)
  94. expect(content)
  95. .toMatch(`props: /*@__PURE__*/_mergeDefaults({ foo: Number, bar: Object, func: Function, ext: null }, {
  96. foo: 1,
  97. bar: () => ({}),
  98. func: () => {}, __skip_func: true,
  99. ext: x, __skip_ext: true
  100. })`)
  101. assertCode(content)
  102. })
  103. test('default values w/ runtime declaration & key is string', () => {
  104. const { content, bindings } = compile(`
  105. <script setup>
  106. const { foo = 1, 'foo:bar': fooBar = 'foo-bar' } = defineProps(['foo', 'foo:bar'])
  107. </script>
  108. `)
  109. expect(bindings).toStrictEqual({
  110. __propsAliases: {
  111. fooBar: 'foo:bar',
  112. },
  113. foo: BindingTypes.PROPS,
  114. 'foo:bar': BindingTypes.PROPS,
  115. fooBar: BindingTypes.PROPS_ALIASED,
  116. })
  117. expect(content).toMatch(`
  118. props: /*@__PURE__*/_mergeDefaults(['foo', 'foo:bar'], {
  119. foo: 1,
  120. "foo:bar": 'foo-bar'
  121. }),`)
  122. assertCode(content)
  123. })
  124. test('default values w/ type declaration', () => {
  125. const { content } = compile(`
  126. <script setup lang="ts">
  127. const { foo = 1, bar = {}, func = () => {} } = defineProps<{ foo?: number, bar?: object, func?: () => any }>()
  128. </script>
  129. `)
  130. // literals can be used as-is, non-literals are always returned from a
  131. // function
  132. expect(content).toMatch(`props: {
  133. foo: { type: Number, required: false, default: 1 },
  134. bar: { type: Object, required: false, default: () => ({}) },
  135. func: { type: Function, required: false, default: () => {} }
  136. }`)
  137. assertCode(content)
  138. })
  139. test('default values w/ type declaration & key is string', () => {
  140. const { content, bindings } = compile(`
  141. <script setup lang="ts">
  142. const { foo = 1, bar = 2, 'foo:bar': fooBar = 'foo-bar' } = defineProps<{
  143. "foo": number // double-quoted string
  144. 'bar': number // single-quoted string
  145. 'foo:bar': string // single-quoted string containing symbols
  146. "onUpdate:modelValue": (val: number) => void // double-quoted string containing symbols
  147. }>()
  148. </script>
  149. `)
  150. expect(bindings).toStrictEqual({
  151. __propsAliases: {
  152. fooBar: 'foo:bar',
  153. },
  154. foo: BindingTypes.PROPS,
  155. bar: BindingTypes.PROPS,
  156. 'foo:bar': BindingTypes.PROPS,
  157. fooBar: BindingTypes.PROPS_ALIASED,
  158. 'onUpdate:modelValue': BindingTypes.PROPS,
  159. })
  160. expect(content).toMatch(`
  161. props: {
  162. foo: { type: Number, required: true, default: 1 },
  163. bar: { type: Number, required: true, default: 2 },
  164. "foo:bar": { type: String, required: true, default: 'foo-bar' },
  165. "onUpdate:modelValue": { type: Function, required: true }
  166. },`)
  167. assertCode(content)
  168. })
  169. test('default values w/ type declaration, prod mode', () => {
  170. const { content } = compile(
  171. `
  172. <script setup lang="ts">
  173. const { foo = 1, bar = {}, func = () => {} } = defineProps<{ foo?: number, bar?: object, baz?: any, boola?: boolean, boolb?: boolean | number, func?: Function }>()
  174. </script>
  175. `,
  176. { isProd: true },
  177. )
  178. assertCode(content)
  179. // literals can be used as-is, non-literals are always returned from a
  180. // function
  181. expect(content).toMatch(`props: {
  182. foo: { default: 1 },
  183. bar: { default: () => ({}) },
  184. baz: {},
  185. boola: { type: Boolean },
  186. boolb: { type: [Boolean, Number] },
  187. func: { type: Function, default: () => {} }
  188. }`)
  189. })
  190. test('with TSInstantiationExpression', () => {
  191. const { content } = compile(
  192. `
  193. <script setup lang="ts">
  194. type Foo = <T extends string | number>(data: T) => void
  195. const { value } = defineProps<{ value: Foo }>()
  196. const foo = value<123>
  197. </script>
  198. `,
  199. { isProd: true },
  200. )
  201. assertCode(content)
  202. expect(content).toMatch(`const foo = __props.value<123>`)
  203. })
  204. test('aliasing', () => {
  205. const { content, bindings } = compile(`
  206. <script setup>
  207. const { foo: bar } = defineProps(['foo'])
  208. let x = foo
  209. let y = bar
  210. </script>
  211. <template>{{ foo + bar }}</template>
  212. `)
  213. expect(content).not.toMatch(`const { foo: bar } =`)
  214. expect(content).toMatch(`let x = foo`) // should not process
  215. expect(content).toMatch(`let y = __props.foo`)
  216. // should convert bar to __props.foo in template expressions
  217. expect(content).toMatch(`_toDisplayString(__props.foo + __props.foo)`)
  218. assertCode(content)
  219. expect(bindings).toStrictEqual({
  220. x: BindingTypes.SETUP_LET,
  221. y: BindingTypes.SETUP_LET,
  222. foo: BindingTypes.PROPS,
  223. bar: BindingTypes.PROPS_ALIASED,
  224. __propsAliases: {
  225. bar: 'foo',
  226. },
  227. })
  228. })
  229. // #5425
  230. test('non-identifier prop names', () => {
  231. const { content, bindings } = compile(`
  232. <script setup>
  233. const { 'foo.bar': fooBar } = defineProps({ 'foo.bar': Function })
  234. let x = fooBar
  235. </script>
  236. <template>{{ fooBar }}</template>
  237. `)
  238. expect(content).toMatch(`x = __props["foo.bar"]`)
  239. expect(content).toMatch(`toDisplayString(__props["foo.bar"])`)
  240. assertCode(content)
  241. expect(bindings).toStrictEqual({
  242. x: BindingTypes.SETUP_LET,
  243. 'foo.bar': BindingTypes.PROPS,
  244. fooBar: BindingTypes.PROPS_ALIASED,
  245. __propsAliases: {
  246. fooBar: 'foo.bar',
  247. },
  248. })
  249. })
  250. test('rest spread', () => {
  251. const { content, bindings } = compile(`
  252. <script setup>
  253. const { foo, bar, ...rest } = defineProps(['foo', 'bar', 'baz'])
  254. </script>
  255. `)
  256. expect(content).toMatch(
  257. `const rest = _createPropsRestProxy(__props, ["foo","bar"])`,
  258. )
  259. assertCode(content)
  260. expect(bindings).toStrictEqual({
  261. foo: BindingTypes.PROPS,
  262. bar: BindingTypes.PROPS,
  263. baz: BindingTypes.PROPS,
  264. rest: BindingTypes.SETUP_REACTIVE_CONST,
  265. })
  266. })
  267. test('rest spread non-inline', () => {
  268. const { content, bindings } = compile(
  269. `
  270. <script setup>
  271. const { foo, ...rest } = defineProps(['foo', 'bar'])
  272. </script>
  273. <template>{{ rest.bar }}</template>
  274. `,
  275. { inlineTemplate: false },
  276. )
  277. expect(content).toMatch(
  278. `const rest = _createPropsRestProxy(__props, ["foo"])`,
  279. )
  280. assertCode(content)
  281. expect(bindings).toStrictEqual({
  282. foo: BindingTypes.PROPS,
  283. bar: BindingTypes.PROPS,
  284. rest: BindingTypes.SETUP_REACTIVE_CONST,
  285. })
  286. })
  287. // #6960
  288. test('computed static key', () => {
  289. const { content, bindings } = compile(`
  290. <script setup>
  291. const { ['foo']: foo } = defineProps(['foo'])
  292. console.log(foo)
  293. </script>
  294. <template>{{ foo }}</template>
  295. `)
  296. expect(content).not.toMatch(`const { foo } =`)
  297. expect(content).toMatch(`console.log(__props.foo)`)
  298. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  299. assertCode(content)
  300. expect(bindings).toStrictEqual({
  301. foo: BindingTypes.PROPS,
  302. })
  303. })
  304. test('multi-variable declaration', () => {
  305. const { content } = compile(`
  306. <script setup>
  307. const { item } = defineProps(['item']),
  308. a = 1;
  309. </script>
  310. `)
  311. assertCode(content)
  312. expect(content).toMatch(`const a = 1;`)
  313. expect(content).toMatch(`props: ['item'],`)
  314. })
  315. // #6757
  316. test('multi-variable declaration fix #6757 ', () => {
  317. const { content } = compile(`
  318. <script setup>
  319. const a = 1,
  320. { item } = defineProps(['item']);
  321. </script>
  322. `)
  323. assertCode(content)
  324. expect(content).toMatch(`const a = 1;`)
  325. expect(content).toMatch(`props: ['item'],`)
  326. })
  327. // #7422
  328. test('multi-variable declaration fix #7422', () => {
  329. const { content } = compile(`
  330. <script setup>
  331. const { item } = defineProps(['item']),
  332. a = 0,
  333. b = 0;
  334. </script>
  335. `)
  336. assertCode(content)
  337. expect(content).toMatch(`const a = 0,`)
  338. expect(content).toMatch(`b = 0;`)
  339. expect(content).toMatch(`props: ['item'],`)
  340. })
  341. test('handle function parameters with same name as destructured props', () => {
  342. const { content } = compile(`
  343. <script setup>
  344. const { value } = defineProps()
  345. function test(value) {
  346. try {
  347. } catch {
  348. }
  349. }
  350. console.log(value)
  351. </script>
  352. `)
  353. assertCode(content)
  354. expect(content).toMatch(`console.log(__props.value)`)
  355. })
  356. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  357. const { content } = compile(`
  358. <script setup>
  359. const props = defineProps(['item']),
  360. emit = defineEmits(['a']);
  361. </script>
  362. `)
  363. assertCode(content)
  364. expect(content).toMatch(`props: ['item'],`)
  365. expect(content).toMatch(`emits: ['a'],`)
  366. })
  367. describe('errors', () => {
  368. test('should error on deep destructure', () => {
  369. expect(() =>
  370. compile(
  371. `<script setup>const { foo: [bar] } = defineProps(['foo'])</script>`,
  372. ),
  373. ).toThrow(`destructure does not support nested patterns`)
  374. expect(() =>
  375. compile(
  376. `<script setup>const { foo: { bar } } = defineProps(['foo'])</script>`,
  377. ),
  378. ).toThrow(`destructure does not support nested patterns`)
  379. })
  380. test('should error on computed key', () => {
  381. expect(() =>
  382. compile(
  383. `<script setup>const { [foo]: bar } = defineProps(['foo'])</script>`,
  384. ),
  385. ).toThrow(`destructure cannot use computed key`)
  386. })
  387. test('should warn when used with withDefaults', () => {
  388. compile(
  389. `<script setup lang="ts">
  390. const { foo } = withDefaults(defineProps<{ foo: string }>(), { foo: 'foo' })
  391. </script>`,
  392. )
  393. expect(
  394. `withDefaults() is unnecessary when using destructure`,
  395. ).toHaveBeenWarned()
  396. })
  397. test('should error if destructure reference local vars', () => {
  398. expect(() =>
  399. compile(
  400. `<script setup>
  401. let x = 1
  402. const {
  403. foo = () => x
  404. } = defineProps(['foo'])
  405. </script>`,
  406. ),
  407. ).toThrow(`cannot reference locally declared variables`)
  408. })
  409. test('should error if assignment to destructured prop binding', () => {
  410. expect(() =>
  411. compile(
  412. `<script setup>
  413. const { foo } = defineProps(['foo'])
  414. foo = 'bar'
  415. </script>`,
  416. ),
  417. ).toThrow(`Cannot assign to destructured props`)
  418. expect(() =>
  419. compile(
  420. `<script setup>
  421. let { foo } = defineProps(['foo'])
  422. foo = 'bar'
  423. </script>`,
  424. ),
  425. ).toThrow(`Cannot assign to destructured props`)
  426. })
  427. test('should error when passing destructured prop into certain methods', () => {
  428. expect(() =>
  429. compile(
  430. `<script setup>
  431. import { watch } from 'vue'
  432. const { foo } = defineProps(['foo'])
  433. watch(foo, () => {})
  434. </script>`,
  435. ),
  436. ).toThrow(
  437. `"foo" is a destructured prop and should not be passed directly to watch().`,
  438. )
  439. expect(() =>
  440. compile(
  441. `<script setup>
  442. import { watch as w } from 'vue'
  443. const { foo } = defineProps(['foo'])
  444. w(foo, () => {})
  445. </script>`,
  446. ),
  447. ).toThrow(
  448. `"foo" is a destructured prop and should not be passed directly to watch().`,
  449. )
  450. expect(() =>
  451. compile(
  452. `<script setup>
  453. import { toRef } from 'vue'
  454. const { foo } = defineProps(['foo'])
  455. toRef(foo)
  456. </script>`,
  457. ),
  458. ).toThrow(
  459. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  460. )
  461. expect(() =>
  462. compile(
  463. `<script setup>
  464. import { toRef as r } from 'vue'
  465. const { foo } = defineProps(['foo'])
  466. r(foo)
  467. </script>`,
  468. ),
  469. ).toThrow(
  470. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  471. )
  472. })
  473. // not comprehensive, but should help for most common cases
  474. test('should error if default value type does not match declared type', () => {
  475. expect(() =>
  476. compile(
  477. `<script setup lang="ts">
  478. const { foo = 'hello' } = defineProps<{ foo?: number }>()
  479. </script>`,
  480. ),
  481. ).toThrow(`Default value of prop "foo" does not match declared type.`)
  482. })
  483. // #8017
  484. test('should not throw an error if the variable is not a props', () => {
  485. expect(() =>
  486. compile(
  487. `<script setup lang='ts'>
  488. import { watch } from 'vue'
  489. const { userId } = defineProps({ userId: Number })
  490. const { error: e, info } = useRequest();
  491. watch(e, () => {});
  492. watch(info, () => {});
  493. </script>`,
  494. ),
  495. ).not.toThrowError()
  496. })
  497. })
  498. })