A robust and modular Svelte project template designed to serve as the foundation for building scalable web applications using an N-Tier architecture. This template provides a clean, organized structure with mock API data providers, making it easy to swap in real API integrations tailored to your specific needs. It is built to be the core for future Svelte-based web applications, with flexibility for updates as technology evolves.
src/lib/data
to simulate backend interactions, allowing easy replacement with real APIs.Clone the repository:
git clone https://github.com/Natubeast/Svelte-Web-App-N-TIER-Template.git
cd Svelte-Web-App-N-TIER-Template
Install dependencies:
npm install
or
pnpm install
Run the development server:
npm run dev
Open your browser at http://localhost:5173
to view the app.
Svelte-Web-App-N-TIER-Template/
├── src/
│ ├── lib/
│ │ ├── components/ # Reusable Svelte components
│ │ ├── data_providers/ # Mock API data providers
│ │ ├── models/ # TypeScript interfaces and data models
│ │ ├── repositories/ # repositories to parse api response into meaningful data for the service layer
│ │ ├── services/ # Business logic and API interaction layer
│ │ ├── states/ # Strongly typed TypeScript classes that control states
│ │ ├── stores/ # All svelte stores, including state stores
│ │ ├── types/ # TypeScript types usually for api responses
│ │ ├── utils/ # Utility functions and helpers
│ │ └── views/ # UI code
│ ├── routes/ # SvelteKit routes and pages
│ ├── test/ # Contains all unit and integration tests
│ └── app.css # Global styles with Tailwind CSS
├── static/ # Static assets (images, fonts, etc.)
├── svelte.config.js # SvelteKit configuration
├── tsconfig.json # TypeScript configuration
├── package.json # Project dependencies and scripts
└── README.md # Project documentation
This template is designed to be a starting point for Svelte web applications. Key steps to customize it for your project:
Replace Mock API Data Providers:
src/lib/data
directory contains mock API responses (e.g., mockDataProvider.ts
). Replace these with real API calls specific to your backend.src/lib/models
to match the structure of your API’s responses.src/lib/services
to handle real API interactions.Update Components:
src/routes
and src/lib/components
to match your UI requirements.Configure Routes:
src/routes
to reflect your application’s navigation structure.Extend Business Logic:
src/lib/services
to handle your application’s specific requirements.Deploy:
npm run build
The application uses Svelte stores for centralized state management, with each feature having its own store:
// src/app/lib/stores/auth.ts
import { writable } from 'svelte/store';
interface AuthState {
isAuthenticated: boolean;
loading: boolean;
error?: string;
}
export const authStore = writable<AuthState>({
isAuthenticated: false,
loading: false
});
Handle all external API communications with proper typing:
// src/app/lib/data-providers/api.ts
interface ApiConfig {
baseUrl: string;
timeout?: number;
}
class ApiDataProvider {
constructor(private config: ApiConfig) {}
async get<T>(endpoint: string): Promise<T> {
// Implementation
}
async post<T>(endpoint: string, data: unknown): Promise<T> {
// Implementation
}
}
Transform raw API data into strongly-typed models:
// src/app/lib/repositories/userRepository.ts
interface UserModel {
id: string;
name: string;
email: string;
}
export class UserRepository {
constructor(private apiProvider: ApiDataProvider) {}
async getUser(id: string): Promise<UserModel> {
const rawData = await this.apiProvider.get(`/users/${id}`);
return this.transformToUserModel(rawData);
}
private transformToUserModel(data: unknown): UserModel {
// Transformation logic
}
}
Contain business logic and orchestrate operations:
// src/app/lib/services/authService.ts
export class AuthService {
constructor(
private userRepository: UserRepository,
private store: Writable<AuthState>
) {}
async login(credentials: LoginCredentials): Promise<void> {
this.store.update(state => ({ ...state, loading: true }));
try {
const user = await this.userRepository.getUserByCredentials(credentials);
this.store.set({
isAuthenticated: true,
loading: false,
currentUser: user
});
} catch (error) {
this.store.update(state => ({
...state,
loading: false,
error: error.message
}));
}
}
}
// src/tests/unit/services/authService.test.ts
import { test, expect } from '@playwright/test';
import { mockStore } from '../mocks/store.mock';
import { AuthService } from '../../app/lib/services/authService';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
service = new AuthService(mockUserRepository, mockStore);
});
test('should handle successful login', async () => {
// Test implementation
});
});
// src/tests/integration/features/login.feature.ts
import { Given, Then, When } from '@cucumber/cucumber';
import { AuthService } from '../../app/lib/services/authService';
Given('the user enters valid credentials', () => {
// Setup
});
When('they submit the login form', () => {
// Action
});
Then('they should be authenticated successfully', () => {
// Assertion
});
Type Safety
State Management
Component Architecture
Testing
Code Organization
npm install svelte @types/svelte typescript jest @testing-library/svelte
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
Contributions are welcome! To contribute:
git checkout -b feature/your-feature
).git commit -m "Add your feature"
).git push origin feature/your-feature
).Please ensure your changes align with the template’s goal of being a reusable, modular foundation for Svelte applications.
This project is licensed under the MIT License. See the LICENSE file for details.
For questions or feedback, open an issue on the GitHub repository or contact the maintainer at natubeast@gmail.com.