My Svelte Code Ordering Style

10 April 2021

Formatting Svelte code with Prettier is just half the story, the script tag is where the magic happens, but there's no formal way to organize it.

Over time I picked up a pattern to help with readabilty, code flow, and familiarity. Feel free to use and tweak it to your own style. YMMV!

Order

  1. Svelte core imports
  2. Svelte third-party library imports
  3. Other library imports
  4. Svelte component imports
  5. Asset imports
  6. Normal JS imports
  7. const variables
  8. export let props
  9. export const props
  10. let variables
  11. Computed variables
  12. Computed blocks
  13. Lifecycle functions
  14. Core logic functions
  15. export function props
  16. Event handler functions
  17. Generic functions

Example

<script>
  import { createEventDispatcher, onMount } from 'svelte'
  import { _ } from 'svelte-i18n'
  import library from 'library'
  import Dashboard from './Dashboard.svelte'
  import picture from './picture.svg'
  import { download } from './utils'

  const MAX_NUMBER = 5
  const dispatch = createEventDispatcher()

  export let value
  export let disabled = false
  export const magicNumber = 10

  let currentNumber = 0

  $: nextNumber = currentNumber + 1

  $: if (currentNumber === magicNumber) {
    console.log(':)')
  }

  onMount(() => {
    currentNumber = -currentNumber
  })

  function calculateSeverity() {
    currentNumber = currentNumber * 5 - 1
  }

  export function reset() {
    currentNumber = -currentNumber
  }

  function handleClick() {
    dispatch('alert')
    boo('alert')
  }

  function boo(str) {
    console.log('[Example] ' + str)
  }
</script>

<Dashboard {value} {disabled} on:click={handleClick} />

© Bjorn Lu 2021