Use Vue 3 Single File Components without compilation

Marcel Leusch
1 min readOct 18, 2021

--

In this article I want to share with you the process of using Single File Components in Vue 3 without compilation. I found some tutorials showing how to do that in Vue 2 but finally I found it out how to do it in Vue 3. Let’s start!

In the first step you have to include vue3-sfc-loader. The simplest way is to use it from CDN.

<script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js"></script>

Next, you have to do some setup stuff to load the file and include the styles. Just copy it and you’ll be happy :)

const { loadModule } = window['vue3-sfc-loader'];

const options = {
moduleCache: {
vue: Vue
},
async getFile(url) {
const res = await fetch(url);
if ( !res.ok )
throw Object.assign(new Error(res.statusText + ' ' + url), { res });
return {
getContentData: asBinary => asBinary ? res.arrayBuffer() : res.text(),
}
},
addStyle(textContent) {
const style = Object.assign(document.createElement('style'), { textContent });
const ref = document.head.getElementsByTagName('style')[0] || null;
document.head.insertBefore(style, ref);
},
}

Now we are ready to import the components in the Vue instance. Here we are using the options constant that we defined in the previous code snippet.

Vue.createApp({
components: {
'my-element': Vue.defineAsyncComponent( () => loadModule('js/components/MyElement.vue', options) )
}
}).mount('#app');

And finally you are ready to use your component in the #app element

<div id="filterModalContainer">
<my-element />
</div>

Believe it or not, that’s all you have to do. The Component code looks exactly the same as you know it from normal Vue projects.

--

--