Is there a way to use pugjs in svelte components?

3.8k Views Asked by At

I'm trying to rewrite my app made with pugjs and express in sveltejs. I really like to write html in pugjs. I was wondering if there is anyway I can use pugjs in svelte components. I am assuming I may need to use svelte-loader and do some preprocessing or is that even possible? I'm using Sapper to rewrite my application in svelte. Can anyone help me how to do that in Sapper?

3

There are 3 best solutions below

1
On BEST ANSWER

I haven't used pug before, but i figure as long as you don't want to translate the pug template into a svelte component (where f.i. pug iteration would be turned into svelte iteration).

So if you can make your pug template a valid svelte component, you should be able to good to go. So including the script tag with logic, and in the outputted html have the {#if|each|await} blocks and {interpolation} blocks.

2
On

There is a Svelte preprocessor wrapper with baked in support for common used preprocessors, including Pug: https://github.com/kaisermann/svelte-preprocess

Here are my pug mixins, including a bonus show mixin (like Vue's v-show). At the bottom you can see how to integrate them with svelte-preprocess.

const pugMixins = `

mixin if(condition)
    | {#if !{condition}}
    block
    | {/if}

mixin else
    | {:else}
    block

mixin elseif(condition)
    | {:elseif !{condition}}
    block

mixin each(loop)
    | {#each !{loop}}
    block
    | {/each}

mixin await(promise)
    | {#await !{promise}}
    block
    | {/await}

mixin then(answer)
    | {:then !{answer}}
    block

mixin catch(error)
    | {:catch !{error}}
    block

mixin debug(variables)
    | {@debug !{variables}}

mixin show(condition)
    div(style!="display: {" + condition + " ? 'initial' : 'none'}")
        block

`

export default {
    /** Transform the whole markup before preprocessing */
    onBefore({ content, filename }) {
        return content.replace('<template lang="pug">', '<template lang="pug">' + pugMixins)
    }
}

0
On

There are a few experimental helper mixins wired into the PUG preprocessor in our fork here:

https://github.com/alvin/sapper-template-pug#pug-mixins

These allow a slightly cleaner syntax with PUG native indentation in loops & conditionals.