How do I design a svelte component to be available in multiple projects?

Viewed 1223

I'm building two web applications in svelte/typescript:

  • Site A that works as the public-facing front that needs to be as fast and lean as possible
  • Site B that is the administration UI where editors update the content that is presented in Site A

I want to use the same "view component" (from Site A) in the editor (in Site B) but attach some editor logic in order to build a WYSIWYG experience without code duplication.

I could of course just make both Site A and Site B be part of the same svelte application but I don't want the visitors of Site A to load all the modules and code used in Site B.

How should I design this to avoid code duplication but still prevent logic from Site B from leaking into Site A?

2 Answers

Let’s say you have an individual project folders for A and B, then you place shared components into a shared-folder, which is sibling to A and B.
When you import shared component to A you just give the import a correct path like ../shared/Comp.svelte. And when you build your project, bundle.js will include only components, that are needed and nothing else.

Best solution for that is to create a design system:

A design system is a collection of reusable components, guided by clear standards, that can be assembled together to build any number of applications.

The implementation is nothing more that creating a npm package. First you will create your design-system repo that contain all your components (Button, Card, ...). Then you will export all of them in a index.js file:

export { Button } from 'path/to/component/Button';
export { Card } from 'path/to/component/Card';
...

Then you bundle your design-system and create a npm package which as the generated index.js file as entry.

Then in your different app you import the components from this package:

import { Button } from 'my-design-system';
Related