Home > Enterprise >  Precompile VueJS template only files
Precompile VueJS template only files

Time:01-06

I am writing a single page app with VueJS. I have a lot of html elements sharing the same style across differents files. To simplify my job and clear the template section I've created .vue files to encapsulate commom html block.

For example I have files like AccentBox.vue:

<template>
    <div >
        <div >
            <slot></slot>
        </div>
    </div>
</template>

The problem is that it increase the bundle size a lot and in the browser side it has a big performance overhead.

Example of the Home.vue:

<Box >
    <GrowingAnimation>
        <Header1>Titre:</Header1>
        <Text >{{todo.title}}</Text>

        <ClickScale>
            <AccentBox >
                <TrashIcon  />
            </AccentBox>
        </ClickScale>
    </Animation>
</Box>

I want to know if there is a way to "precompile / transform" those component so that in the browser vuejs does not have to render the AccentBox.vue component and avoid having huge trees of nested vuejs components.

I already use the vuejs build command but browser side AccentBox.vue still is a component and take time to be processed by vue.

Transforming this:

<Header1>Titre:</Header1>

into

<h1 >Titre:</h1>

Is there any way to do it? Thanks in advance.

CodePudding user response:

Because your AccentBox.vue file represents a full-blown component, it does contain more overhead than simply writing out some divs. However, in Vue 3, this overhead is rather minimal, and there isn't a way to precompile something like a macro.

Vue allows us to write stateless components that simply render HTML, using something called a render function. We can rewrite your AccentBox component like this:

import { h } from 'vue'

const AccentBox = (props, context) => {
  return h(
    'div',
    { class: 'bg-accent rounded-lg p-4 flex cursor-pointer' },
    h(
      'div',
      { class: 'm-auto flex flex-row' },
      context.slots
    )
  )
}

export default AccentBox

We can then import it in exactly the same way as a standard Vue file:

import AccentBox from 'AccentBox.js'
  • Related