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 Answers
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)
}
}

- 2,048
- 2
- 17
- 13
-
1the svelte-preprocess package has added pug mixins natively using a similar method to yours – Matthew Jul 10 '19 at 18:43
-
@MatthewPrasinov Thanks, I didn't know. The `show` mixin above is still missing and nice to add ;) – Laurent Payot Jul 11 '19 at 10:13
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.

- 3
- 1

- 41
- 2
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.

- 26
- 2
-
Yes I'm doing that already, just forgot to answer my own question. – anoop chandran Jun 02 '18 at 12:46