Search code examples
svelte-3svelte-component

Svelte namespace components export


In docs there is a Tags section with such stuff:

A lowercase tag, like <div>, denotes a regular HTML element. A capitalised tag, such as <Widget> or <Namespace.Widget>, indicates a component.

How export such <Namespace.Widget> or <Namespace.Whatever>?


Solution

  • So I think what this is referring to is when you export multiple .svelte files from a single .js file and import them all under a single namespace in another component... It's not very well documented but it works.

    If you have the following project structure:

    ─ src/
      ├── child/
      │   ├── index.js
      │   ├── One.svelte
      │   └── Two.svelte
      └── Parent.svelte
    

    In child/index.js export the 2 components inside the same folder:

    export { default as One } from './One.svelte'
    export { default as Two } from './Two.svelte'
    

    Then in Parent.svelte import all of the components under a single namespace instead of importing each individual component:

    <script>
      import * as Something from './child'
    </script>
    
    <Something.One />
    <Something.Two />
    

    You can test the functionality in the REPL like this one https://svelte.dev/repl/18f41adb56fa46ff8b25cad7c1a388a4?version=3.38.3 it's just not as useful without a proper file structure.