Import defaults in Vue SFC for withDefaults
# ni
ni -D vite-plugin-vue-with-defaults-imports
# npm
npm i -D vite-plugin-vue-with-defaults-imports
# yarn
yarn add -D vite-plugin-vue-with-defaults-imports
# pnpm
pnpm add -D vite-plugin-vue-with-defaults-imports
// vite.config.ts
import { defineConfig } from 'vite';
import Vue from '@vitejs/plugin-vue';
import VueWithDefaultsImports from 'vite-plugin-vue-with-defaults-imports';
export default defineConfig({
plugins: [Vue(), VueWithDefaultsImports()],
});
<script setup lang="ts">
import { propsDefaults } from './defaults';
interface Props {
foo: string;
bar: number;
}
const props = withDefaults(defineProps<Props>(), propsDefaults);
</script>
// defaults.ts
export const propsDefaults = {
foo: 'foo',
bar: 1,
};
Output
<script setup lang="ts">
import { propsDefaults } from './defaults';
interface Props {
foo: string;
bar: number;
}
const props = withDefaults(defineProps<Props>(), { ...propsDefaults });
</script>
How it works is very simple, it just turns defaults
into { ...defaults }
to force Vue to fallback to runtime merging