definePropsDestructure.spec.ts 15 KB

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