definePropsDestructure.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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('aliasing', () => {
  191. const { content, bindings } = compile(`
  192. <script setup>
  193. const { foo: bar } = defineProps(['foo'])
  194. let x = foo
  195. let y = bar
  196. </script>
  197. <template>{{ foo + bar }}</template>
  198. `)
  199. expect(content).not.toMatch(`const { foo: bar } =`)
  200. expect(content).toMatch(`let x = foo`) // should not process
  201. expect(content).toMatch(`let y = __props.foo`)
  202. // should convert bar to __props.foo in template expressions
  203. expect(content).toMatch(`_toDisplayString(__props.foo + __props.foo)`)
  204. assertCode(content)
  205. expect(bindings).toStrictEqual({
  206. x: BindingTypes.SETUP_LET,
  207. y: BindingTypes.SETUP_LET,
  208. foo: BindingTypes.PROPS,
  209. bar: BindingTypes.PROPS_ALIASED,
  210. __propsAliases: {
  211. bar: 'foo',
  212. },
  213. })
  214. })
  215. // #5425
  216. test('non-identifier prop names', () => {
  217. const { content, bindings } = compile(`
  218. <script setup>
  219. const { 'foo.bar': fooBar } = defineProps({ 'foo.bar': Function })
  220. let x = fooBar
  221. </script>
  222. <template>{{ fooBar }}</template>
  223. `)
  224. expect(content).toMatch(`x = __props["foo.bar"]`)
  225. expect(content).toMatch(`toDisplayString(__props["foo.bar"])`)
  226. assertCode(content)
  227. expect(bindings).toStrictEqual({
  228. x: BindingTypes.SETUP_LET,
  229. 'foo.bar': BindingTypes.PROPS,
  230. fooBar: BindingTypes.PROPS_ALIASED,
  231. __propsAliases: {
  232. fooBar: 'foo.bar',
  233. },
  234. })
  235. })
  236. test('rest spread', () => {
  237. const { content, bindings } = compile(`
  238. <script setup>
  239. const { foo, bar, ...rest } = defineProps(['foo', 'bar', 'baz'])
  240. </script>
  241. `)
  242. expect(content).toMatch(
  243. `const rest = _createPropsRestProxy(__props, ["foo","bar"])`,
  244. )
  245. assertCode(content)
  246. expect(bindings).toStrictEqual({
  247. foo: BindingTypes.PROPS,
  248. bar: BindingTypes.PROPS,
  249. baz: BindingTypes.PROPS,
  250. rest: BindingTypes.SETUP_REACTIVE_CONST,
  251. })
  252. })
  253. test('rest spread non-inline', () => {
  254. const { content, bindings } = compile(
  255. `
  256. <script setup>
  257. const { foo, ...rest } = defineProps(['foo', 'bar'])
  258. </script>
  259. <template>{{ rest.bar }}</template>
  260. `,
  261. { inlineTemplate: false },
  262. )
  263. expect(content).toMatch(
  264. `const rest = _createPropsRestProxy(__props, ["foo"])`,
  265. )
  266. assertCode(content)
  267. expect(bindings).toStrictEqual({
  268. foo: BindingTypes.PROPS,
  269. bar: BindingTypes.PROPS,
  270. rest: BindingTypes.SETUP_REACTIVE_CONST,
  271. })
  272. })
  273. // #6960
  274. test('computed static key', () => {
  275. const { content, bindings } = compile(`
  276. <script setup>
  277. const { ['foo']: foo } = defineProps(['foo'])
  278. console.log(foo)
  279. </script>
  280. <template>{{ foo }}</template>
  281. `)
  282. expect(content).not.toMatch(`const { foo } =`)
  283. expect(content).toMatch(`console.log(__props.foo)`)
  284. expect(content).toMatch(`_toDisplayString(__props.foo)`)
  285. assertCode(content)
  286. expect(bindings).toStrictEqual({
  287. foo: BindingTypes.PROPS,
  288. })
  289. })
  290. test('multi-variable declaration', () => {
  291. const { content } = compile(`
  292. <script setup>
  293. const { item } = defineProps(['item']),
  294. a = 1;
  295. </script>
  296. `)
  297. assertCode(content)
  298. expect(content).toMatch(`const a = 1;`)
  299. expect(content).toMatch(`props: ['item'],`)
  300. })
  301. // #6757
  302. test('multi-variable declaration fix #6757 ', () => {
  303. const { content } = compile(`
  304. <script setup>
  305. const a = 1,
  306. { item } = defineProps(['item']);
  307. </script>
  308. `)
  309. assertCode(content)
  310. expect(content).toMatch(`const a = 1;`)
  311. expect(content).toMatch(`props: ['item'],`)
  312. })
  313. // #7422
  314. test('multi-variable declaration fix #7422', () => {
  315. const { content } = compile(`
  316. <script setup>
  317. const { item } = defineProps(['item']),
  318. a = 0,
  319. b = 0;
  320. </script>
  321. `)
  322. assertCode(content)
  323. expect(content).toMatch(`const a = 0,`)
  324. expect(content).toMatch(`b = 0;`)
  325. expect(content).toMatch(`props: ['item'],`)
  326. })
  327. test('defineProps/defineEmits in multi-variable declaration (full removal)', () => {
  328. const { content } = compile(`
  329. <script setup>
  330. const props = defineProps(['item']),
  331. emit = defineEmits(['a']);
  332. </script>
  333. `)
  334. assertCode(content)
  335. expect(content).toMatch(`props: ['item'],`)
  336. expect(content).toMatch(`emits: ['a'],`)
  337. })
  338. describe('errors', () => {
  339. test('should error on deep destructure', () => {
  340. expect(() =>
  341. compile(
  342. `<script setup>const { foo: [bar] } = defineProps(['foo'])</script>`,
  343. ),
  344. ).toThrow(`destructure does not support nested patterns`)
  345. expect(() =>
  346. compile(
  347. `<script setup>const { foo: { bar } } = defineProps(['foo'])</script>`,
  348. ),
  349. ).toThrow(`destructure does not support nested patterns`)
  350. })
  351. test('should error on computed key', () => {
  352. expect(() =>
  353. compile(
  354. `<script setup>const { [foo]: bar } = defineProps(['foo'])</script>`,
  355. ),
  356. ).toThrow(`destructure cannot use computed key`)
  357. })
  358. test('should error when used with withDefaults', () => {
  359. expect(() =>
  360. compile(
  361. `<script setup lang="ts">
  362. const { foo } = withDefaults(defineProps<{ foo: string }>(), { foo: 'foo' })
  363. </script>`,
  364. ),
  365. ).toThrow(`withDefaults() is unnecessary when using destructure`)
  366. })
  367. test('should error if destructure reference local vars', () => {
  368. expect(() =>
  369. compile(
  370. `<script setup>
  371. let x = 1
  372. const {
  373. foo = () => x
  374. } = defineProps(['foo'])
  375. </script>`,
  376. ),
  377. ).toThrow(`cannot reference locally declared variables`)
  378. })
  379. test('should error if assignment to destructured prop binding', () => {
  380. expect(() =>
  381. compile(
  382. `<script setup>
  383. const { foo } = defineProps(['foo'])
  384. foo = 'bar'
  385. </script>`,
  386. ),
  387. ).toThrow(`Cannot assign to destructured props`)
  388. expect(() =>
  389. compile(
  390. `<script setup>
  391. let { foo } = defineProps(['foo'])
  392. foo = 'bar'
  393. </script>`,
  394. ),
  395. ).toThrow(`Cannot assign to destructured props`)
  396. })
  397. test('should error when passing destructured prop into certain methods', () => {
  398. expect(() =>
  399. compile(
  400. `<script setup>
  401. import { watch } from 'vue'
  402. const { foo } = defineProps(['foo'])
  403. watch(foo, () => {})
  404. </script>`,
  405. ),
  406. ).toThrow(
  407. `"foo" is a destructured prop and should not be passed directly to watch().`,
  408. )
  409. expect(() =>
  410. compile(
  411. `<script setup>
  412. import { watch as w } from 'vue'
  413. const { foo } = defineProps(['foo'])
  414. w(foo, () => {})
  415. </script>`,
  416. ),
  417. ).toThrow(
  418. `"foo" is a destructured prop and should not be passed directly to watch().`,
  419. )
  420. expect(() =>
  421. compile(
  422. `<script setup>
  423. import { toRef } from 'vue'
  424. const { foo } = defineProps(['foo'])
  425. toRef(foo)
  426. </script>`,
  427. ),
  428. ).toThrow(
  429. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  430. )
  431. expect(() =>
  432. compile(
  433. `<script setup>
  434. import { toRef as r } from 'vue'
  435. const { foo } = defineProps(['foo'])
  436. r(foo)
  437. </script>`,
  438. ),
  439. ).toThrow(
  440. `"foo" is a destructured prop and should not be passed directly to toRef().`,
  441. )
  442. })
  443. // not comprehensive, but should help for most common cases
  444. test('should error if default value type does not match declared type', () => {
  445. expect(() =>
  446. compile(
  447. `<script setup lang="ts">
  448. const { foo = 'hello' } = defineProps<{ foo?: number }>()
  449. </script>`,
  450. ),
  451. ).toThrow(`Default value of prop "foo" does not match declared type.`)
  452. })
  453. // #8017
  454. test('should not throw an error if the variable is not a props', () => {
  455. expect(() =>
  456. compile(
  457. `<script setup lang='ts'>
  458. import { watch } from 'vue'
  459. const { userId } = defineProps({ userId: Number })
  460. const { error: e, info } = useRequest();
  461. watch(e, () => {});
  462. watch(info, () => {});
  463. </script>`,
  464. ),
  465. ).not.toThrowError()
  466. })
  467. })
  468. })