definePropsDestructure.spec.ts 14 KB

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