A modern template for Svelte projects using TypeScript and Vite as a bundler. This repository serves as a starting point for new Svelte projects with an optimized, ready-to-use configuration.
This template includes:
- Svelte 5 with TypeScript support
- Vite for fast development and optimized build
- Skeleton UI integration
- Enhanced dark/light theme system with CSS variables
- Organized project structure
- Internationalization (i18n) support
- Comprehensive unit and E2E tests
- CI/CD with GitHub Actions for GitHub Pages deployment
-
Using GitHub
# Clone this template gh repo create my-project --template svelte-ts-skeleton-starter # or use GitHub's interface to create a new repository from this template
-
Manually
# Clone the repository git clone https://github.com/your-username/svelte-ts-skeleton-starter.git my-project # Remove Git history cd my-project rm -rf .git # Initialize a new Git repository git init
-
Project Initialization
npm create vite@latest svelte-ts-skeleton-starter -- --template svelte-ts cd svelte-ts-skeleton-starter npm install -
Project Structure
📦 svelte-ts-skeleton-starter ├── 📂 public/ │ └── vite.svg ├── 📂 src/ │ ├── 📂 assets/ │ │ └── svelte.svg │ ├── 📂 lib/ │ │ └── Counter.svelte │ ├── 📂 styles/ │ │ └── global.css │ ├── app.css │ ├── App.svelte │ ├── main.ts │ └── vite-env.d.ts ├── index.html ├── package.json ├── svelte.config.js ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts
svelte: ^5.23.1@skeletonlabs/skeleton: ^3.1.3svelte-i18n: ^4.0.0 # Internationalization library
@sveltejs/vite-plugin-svelte: ^5.0.3@tsconfig/svelte: ^5.0.4svelte-check: ^4.1.5typescript: ~5.7.2vite: ^6.3.1
{
"dev": "vite", // Starts the development server
"build": "vite build", // Generates production build
"preview": "vite preview", // Preview production version
"check": "svelte-check" // Runs TypeScript type checking
}- Visual Studio Code with Svelte for VS Code extension
- VS Code
- Svelte Extension
The project uses TypeScript with the following main configurations:
- Full TypeScript support in Svelte components
- Optimized configuration for Svelte development
- Integrated type checking
-
Clone the repository
git clone [REPOSITORY-URL]
-
Install dependencies
npm install
-
Start the development server
npm run dev
-
Access the project The project will be available at
http://localhost:5173
/public: Static files that will be served directly/src: Application source code/assets: Resources such as images and icons/components: User interface componentsLanguageSelector.svelte: Component for language switchingThemeToggle.svelte: Enhanced component for toggling between light/dark themes with improved accessibility, theme persistence, and error handling
/lib: Reusable components and shared functionalitiesi18n.ts: Internationalization system/locales: Translation files for different languagesen.ts: English translationspt.ts: Portuguese translationses.ts: Spanish translations
/styles: Global style filesApp.svelte: Root application componentmain.ts: Application entry point
- Extremely fast Hot Module Replacement (HMR)
- Zero configuration to start
- Native TypeScript support
- Optimized production build
The project uses TypeScript for:
- Better development experience
- Real-time type checking
- Better IDE support
- More secure and maintainable code
This project includes a complete setup for unit and end-to-end (E2E) tests.
We use Vitest for unit tests with the following features:
- Integration with the Svelte ecosystem
- Support for Svelte components
- Code coverage report generation
- JSDOM-based test environment
- Mock tests for external modules
Available commands:
# Run tests in watch mode (development)
npm test
# Run tests once
npm run test:run
# Run tests with coverage report
npm run test:coverage
npm run coverageThe internationalization system has comprehensive unit tests that verify:
- Correct initialization of the i18n system
- Browser language detection
- User preferences persistence
- Loading and access to translations
- Consistency of translation keys across different languages
- Appropriate behavior when translation keys don't exist
We use Playwright for E2E tests with the following features:
- Support for multiple browsers (Chrome, Firefox, Safari)
- Accessibility tests
- Detailed execution reports
- Specific tests for internationalization functionalities
Available commands:
# Run all E2E tests
npm run e2e
# Run E2E tests with visual interface
npm run e2e:ui
# View E2E test report
npm run e2e:reportThe E2E tests for internationalization ensure that:
- Language selectors are present and functional in the interface
- Language changes correctly update the page content
- Language preferences are persisted between reloads
- Text elements appear correctly in the selected language
- Accessibility is maintained when switching between languages
These tests use an approach based on the role and name of elements (getByRole, getByText), which makes the tests more robust and less susceptible to breaking due to changes in HTML or CSS structure.
The project includes specific accessibility tests for:
- Appropriate header structure
- Keyboard navigation
- Appropriate ARIA attributes
- Color contrast
- Language selector accessibility
To run all tests (unit and E2E) at once:
npm run test:allTo build the project for production:
npm run buildThe built files will be available in the dist/ directory.
This template supports automatic deployment to GitHub Pages with comprehensive testing integration.
-
Configure GitHub Pages in your repository settings:
- Go to repository Settings → Pages
- Under Source, select GitHub Actions
- Save the configuration
-
Update
vite.config.tswith your repository name:export default defineConfig({ plugins: [svelte()], base: '/your-repository-name/', // Replace with your repository name // other configurations });
The deployment workflow (.github/workflows/deploy.yml) automatically:
- ✅ Triggers on every push to
mainbranch - ✅ Runs comprehensive tests before deployment
- ✅ Deploys only when tests pass
- ✅ Includes unit and E2E testing
- ✅ Provides complete deployment history
- ✅ Supports manual triggering via GitHub Actions interface
The automated deployment includes:
- Environment Setup: Node.js 20 with npm caching
- Dependency Installation:
npm cifor reproducible builds - Unit Testing: Validates component functionality
- E2E Testing: End-to-end testing with Playwright across multiple browsers
- Build Generation: Production-optimized build
- GitHub Pages Deployment: Automatic publishing to GitHub Pages
You can also trigger deployment manually:
- Go to repository Actions tab
- Select Deploy to GitHub Pages workflow
- Click Run workflow
- Confirm the deployment
For GitHub Pages deployment, ensure your vite.config.ts includes the correct base path:
export default defineConfig({
plugins: [svelte()],
base: process.env.NODE_ENV === 'production' ? '/your-repo-name/' : '/',
// other configurations
});For different deployment environments:
// vite.config.ts
export default defineConfig({
plugins: [svelte()],
base: process.env.VITE_BASE_URL || '/',
define: {
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
},
});The deployment process includes comprehensive testing:
- Unit Tests: Component functionality and logic validation using Vitest
- E2E Tests: End-to-end user interaction testing with Playwright
- Cross-Browser Testing: Validation across Chromium, Firefox, and WebKit
- Accessibility Tests: Automated accessibility validation with axe-core
- Build Validation: Ensures the application builds successfully
- Base URL Problems: Ensure the
baseconfiguration matches your repository name - Asset Loading: Use relative paths for assets and images
- Test Failures: Check the Actions tab for detailed test failure logs
- Permission Issues: Ensure GitHub Actions has proper permissions
- Check the Actions tab in your GitHub repository
- Review the workflow logs for specific error messages
- Ensure all tests pass locally before pushing:
npm run test:run # Run unit tests npm run e2e # Run E2E tests npm run build # Test build process
- Verify the
baseURL configuration
To use a custom domain with GitHub Pages:
- Add a
CNAMEfile to thepublic/directory with your domain - Configure DNS settings with your domain provider
- Update the
baseconfiguration if needed
main: Main development branch with automatic deploymentgh-pages: Automatically managed deployment branch (do not edit manually)
The workflow uses GitHub's native Pages deployment action, eliminating the need for manual branch management.
- Fork the project
- Create a branch for your feature (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
For questions and support, please open an issue in the project repository.
The template now includes an improved theme system with the following features:
-
Robust Dark/Light Mode: Implements theme switching using multiple approaches simultaneously:
- CSS Variables with
data-modeattribute - Tailwind Dark Mode with
darkclass - Skeleton UI themes with
data-themeattribute - Automatic theme persistence using localStorage
- CSS Variables with
-
Flash Prevention: Includes script in HTML to apply theme immediately during page load, preventing flash of wrong theme
-
Error Handling: Built-in fallbacks if localStorage is unavailable
-
Accessibility: Improved accessibility with proper ARIA attributes on theme toggle controls
-
Comprehensive Tests: Enhanced test coverage for theme functionality including error handling
The theme system provides a simple API through the ThemeToggle component:
<script>
import ThemeToggle from './components/ThemeToggle.svelte';
</script>
<ThemeToggle />Custom styling can be applied using the CSS variables defined in src/styles/global.css:
:root {
--app-background: #ffffff;
--app-text: #1a202c;
/* other variables */
}
[data-mode="dark"] {
--app-background: #0f172a;
--app-text: #f8fafc;
/* other dark mode variables */
}The theme system uses a multi-layered approach to ensure comprehensive theming:
-
CSS Custom Properties (Variables)
- Defined in
src/styles/global.css - Allows custom styling with semantic variables like
--app-backgroundand--app-text - Variables change based on the
data-modeattribute
- Defined in
-
HTML Data Attributes
data-mode: Controls the main theme ('light' or 'dark')data-theme: Controls the Skeleton UI theme ('skeleton' for light, 'vintage' for dark)
-
CSS Class
- The
darkclass is added tohtmlelement for Tailwind dark mode - Enables the use of
dark:variant in Tailwind classes
- The
-
Local Storage Persistence
- Theme preference is saved in
localStorageas 'mode' - Automatically restored on page load
- Includes error handling for privacy modes
- Theme preference is saved in
-
Initialization
- Theme is applied immediately during page load in
index.html - Prevents flash of incorrect theme on initial load
- Theme is applied immediately during page load in
-
Accessibility
- Theme toggle uses proper ARIA attributes
- Keyboard navigable
- Maintains color contrast standards
See src/components/ThemeToggle.example.ts for examples of how to extend the theme system.
-
Correção da API de Eventos do Svelte 5
- Atualizado o uso de
on:clickparaonclickconforme recomendado pela API do Svelte 5 - Esta mudança afeta os componentes ThemeToggle e LanguageSelector
- Atualizado o uso de
-
Ajustes no Sistema de Temas
- Removidas importações problemáticas de temas específicos do Skeleton UI
- Mantida a funcionalidade de tema usando variáveis CSS e atributos data-mode/data-theme
- Corrigida a forma como o ThemeToggle é renderizado no App.svelte
-
Compatibilidade com Testes E2E
- Garantido que os elementos esperados pelos testes E2E estão presentes no DOM
- Mantida a estrutura correta de cabeçalhos para testes de acessibilidade
Para executar os testes após estas correções:
# Teste unitários
npm run test:run
# Testes E2E
npm run e2e