Razvan Zamfir
Razvan Zamfir

Reputation: 4616

How can I use the Smelte material design library for Svelte.js in an effective, dry, manner?

I am working on a project with Svelte and the material design library Smelte. According to the Smelte docs (smeltejs.com), I have to import every component in every file I want/need to use it, for example, in src\pages\index.svelte:

<script>
  import Button from "smelte/src/components/Button";
  import Icon from "smelte/src/components/Icon";
</script>

Using the lines above in src\App.svelte does not work.

This is rather tedious and ineffective. Many of the library's components are needed in every page.

How can I instead import all (or most) of the library's components and be able to use them in any file?

Upvotes: 0

Views: 1326

Answers (1)

JHeth
JHeth

Reputation: 8366

If you really just want a simple one-line import for everything in Smelte and you don't give a hoot about tree-shaking you can always import * as Smelte from 'smelte' in your script tag substituting Smelte for whatever you want the component tag modifier to be.

In order to use the components you need to use the modifier like so <Smelte.Button>

Here's a REPL showing it off (minus the Smelte styling).

However, if you want to only import some as a single statement you can do a similar trick and only export the ones you need from a separate JS file. There's plenty of ways to export it but the following would be one:

// somefile.js
import Button from "smelte/src/components/Button"
import Treeview from "smelte/src/components/Treeview"

export {
  Button,
  Treeview
}

Then inside your Svelte files you can import * as Smelte from './somefile.js' and access those components in the same way as the first method.

Here's a REPL for that as well.

Pretty sure both ways would present some treeshaking complications but your script tags will be less cluttered and you won't have to worry about importing every single part you need.

Upvotes: 2

Related Questions