A modern web component built with Svelte, TypeScript, and Vite. This template creates a reusable custom element that can be used in any web application.
<svelte-vite-app>
)Install dependencies:
npm install
Start development server:
npm run dev
Build for production:
npm run build
Preview the built version:
npm run preview:bundled
<script type="module" src="/dist/svelte-vite-app.es.js"></script>
<svelte-vite-app></svelte-vite-app>
<script src="/dist/svelte-vite-app.umd.js"></script>
<svelte-vite-app></svelte-vite-app>
import 'webcomponent-svelte'
// The custom element is now registered and ready to use
document.body.innerHTML = '<svelte-vite-app></svelte-vite-app>'
require('webcomponent-svelte')
npm run dev
- Start development server with HMRnpm run build
- Build for productionnpm run preview
- Preview the production buildnpm run preview:bundled
- Preview the built web component demonpm run format
- Format code with Prettiernpm run format:check
- Check code formattingnpm run check
- Type-check TypeScript filessrc/FutureEdMobilityExplorer.wc.svelte
- Main web component implementationsrc/main.ts
- Web component registration and exportsbundled.html
- Demo page for the built web componentvite.config.ts
- Build and development configurationvite.preview.config.ts
- Preview server configurationCheck out SvelteKit, which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
Why use this over SvelteKit?
This template is optimized for building web components with Svelte. It includes all the necessary configuration for:
Why global.d.ts
instead of compilerOptions.types
inside jsconfig.json
or tsconfig.json
?
Setting compilerOptions.types
shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding svelte
and vite/client
type information.
Why include .vscode/extensions.json
?
Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
Special Configuration Details
Vite Configuration
.wc.svelte
) and one for regular Svelte components@
points to src
)Package.json Configuration
Why is HMR not preserving my local component state?
HMR state preservation comes with a number of gotchas! It has been disabled by default in both svelte-hmr
and @sveltejs/vite-plugin-svelte
due to its often surprising behavior. You can read the details here.
If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
// store.ts
// An extremely simple external store
import { writable } from 'svelte/store'
export default writable(0)