[Vuejs]-Build an Vue app based on modules that may be missing

1👍

It’s quite easy to solve this with a rollup plugin. The plugin could be written right inside vite.config.js. Here you use the rollup hook resolveId. The Vite/Rollup calls this hook when it cannot resolve an import. If it’s a Vue SFC you resolve it to any placeholder component of choice:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        {
            resolveId(id) {
                if (id.endsWith('.vue')) {
                    return './src/components/Placeholder.vue';
                }
            },
        }
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    }
})


App.vue with some non-existing component:

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
import MissingComponent from './components/MissingComponent.vue'
</script>

<template>
    <header>
        <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />

        <div class="wrapper">
            <HelloWorld msg="You did it!" />
            <MissingComponent />
        </div>
    </header>

    <main>
        <TheWelcome />
    </main>
</template>

src/components/Placeholder.vue (if you want it empty just do <template></template>):

<template>
    That's a placeholder for missing component, could be empty...
</template>

Result:

enter image description here

The only problem is that HMR doesn’t work if you change the Placeholder.vue, but that’s not a problem I guess because it’s just a placeholder…

Leave a comment