Skip to content

dynamically import components? #5597

Answered by hartwm
tryggs asked this question in Q&A
Jul 18, 2022 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

Here is an example based on page params

<script lang="ts" > 
  import {page} from '$app/stores'
  let imports = import.meta.glob(`/src/page/*.svelte`)
  let defaultContent = imports[`/src/page/base.svelte`]  
  $: dynamicContent = imports[`/src/page/${$page.params.uri}.svelte`] 
  $: component = (dynamicContent) ? dynamicContent : defaultContent
</script>  

<div class="page-content">   
  {#await component() then module}
    <svelte:component this={module.default} {post} />
  {/await}  
</div>

with page being the directory of the components you are looking to import

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@tryggs
Comment options

@PlopTheReal
Comment options

Answer selected by tryggs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants