mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
---
|
||||
description: Comprehensive Svelte best practices covering code structure, performance, security, testing, and common pitfalls. This rule provides guidance on writing maintainable, efficient, and secure Svelte applications.
|
||||
globs: **/*.svelte
|
||||
---
|
||||
- **Manipulate the DOM with HTML:** Utilize Svelte's HTML-centric approach to manipulate the DOM.
|
||||
- **Solve challenges with HTML/CSS first:** Prioritize solving problems with HTML and CSS before resorting to JavaScript.
|
||||
- **Write short components:** Aim for concise and focused components to improve readability and maintainability.
|
||||
- **Write concise reactive `$:` blocks:** Keep reactive statements short and easy to understand.
|
||||
- **Scope CSS to the actual component:** Ensure that CSS styles are scoped to the component to avoid conflicts.
|
||||
- **Avoid hard coding data or dimensions:** Use dynamic data and responsive design techniques instead of hard-coded values.
|
||||
- **Keep objects immutable:** Treat objects as immutable to prevent unexpected side effects and improve performance.
|
||||
- **Use two-way binding effectively:** Leverage two-way binding for efficient data synchronization but be mindful of its potential impact on performance for complex scenarios.
|
||||
|
||||
## 1. Code Organization and Structure:
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- `src/`: Contains all the application source code.
|
||||
- `src/components/`: Holds reusable Svelte components, categorized further by feature or domain (e.g., `src/components/Button/`, `src/components/Form/`).
|
||||
- `src/lib/`: Contains utility functions, helper modules, and reusable logic that is not specific to a component.
|
||||
- `src/routes/`: For SvelteKit applications, this directory defines the application's routes.
|
||||
- `src/stores/`: Stores for global state management (if using Svelte's stores).
|
||||
- `static/`: Static assets like images, fonts, and other resources.
|
||||
- **File Naming Conventions:**
|
||||
- Components: Use PascalCase (e.g., `MyComponent.svelte`).
|
||||
- Utility functions: Use camelCase (e.g., `formatDate.js`).
|
||||
- Stores: Use descriptive names related to the data they hold (e.g., `userStore.js`).
|
||||
- **Module Organization:**
|
||||
- Group related components and utilities into modules within their respective directories.
|
||||
- Use `index.js` or `index.svelte` files to export multiple components or functions from a directory, providing a cleaner import experience.
|
||||
- **Component Architecture:**
|
||||
- Favor a component-based architecture where UI is broken down into small, reusable components.
|
||||
- Consider using a composition pattern where complex components are built by composing simpler ones.
|
||||
- Separate concerns: Keep components focused on presentation logic and delegate data fetching or business logic to services or stores.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`import()`) to load components or modules on demand, reducing the initial bundle size.
|
||||
- Leverage SvelteKit's built-in code splitting capabilities for route-based splitting.
|
||||
- Consider splitting large components into smaller, lazily loaded sub-components.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns:
|
||||
|
||||
- **Design Patterns Specific to Svelte:**
|
||||
- **Store pattern:** Use Svelte's stores for managing application state and reactivity.
|
||||
- **Action pattern:** Use Svelte's actions for manipulating DOM elements or integrating with third-party libraries.
|
||||
- **Component composition:** Build complex UIs by composing smaller, reusable components.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Form handling:** Use Svelte's two-way binding (`bind:value`) for simple forms. For more complex scenarios, consider libraries like Formik or Svelte Formly.
|
||||
- **Data fetching:** Use `fetch` or libraries like Axios for fetching data from APIs. Handle loading and error states appropriately.
|
||||
- **Event handling:** Use Svelte's event directives (e.g., `on:click`) for handling DOM events.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Overusing global state:** Avoid putting everything in a global store. Use component-level state when appropriate.
|
||||
- **Directly manipulating the DOM outside of actions:** Rely on Svelte's reactivity system to update the DOM.
|
||||
- **Writing overly complex components:** Break down large components into smaller, more manageable ones.
|
||||
- **State Management Best Practices:**
|
||||
- Use Svelte's built-in stores for managing global or application-level state.
|
||||
- Consider using reactive declarations (`$:`) to derive state from other state variables.
|
||||
- Keep state updates predictable and avoid modifying state directly.
|
||||
- For complex state management needs, explore libraries like Redux or Zustand (though often unnecessary in Svelte).
|
||||
- **Error Handling Patterns:**
|
||||
- Use try-catch blocks to handle potential errors during data fetching or other asynchronous operations.
|
||||
- Display user-friendly error messages in the UI.
|
||||
- Log errors to the console or a logging service for debugging purposes.
|
||||
- Implement global error handling to catch unhandled exceptions.
|
||||
|
||||
## 3. Performance Considerations:
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Minimize DOM updates:** Svelte is very efficient at updating the DOM, but unnecessary updates can still impact performance. Use reactive declarations judiciously.
|
||||
- **Use `{#each}` blocks efficiently:** Key your `{#each}` blocks with unique identifiers to help Svelte efficiently update the list.
|
||||
- **Avoid unnecessary component re-renders:** Use the `$:` syntax effectively to only update components when necessary.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up event listeners and subscriptions when components are destroyed (using `onDestroy`).
|
||||
- Be mindful of large data structures in stores, and consider using techniques like pagination or virtualization to manage them efficiently.
|
||||
- **Rendering Optimization:**
|
||||
- Use the `svelte:options` tag with the `immutable` option for components that receive immutable data as props.
|
||||
- Use `shouldUpdate` to prevent rendering for unchanged immutable props.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use production builds with minification and tree shaking to remove unused code.
|
||||
- Use dynamic imports for code splitting.
|
||||
- Optimize images and other assets.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use dynamic imports to lazy load components or modules that are not immediately needed.
|
||||
- Implement lazy loading for images or other resources that are below the fold.
|
||||
|
||||
## 4. Security Best Practices:
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Cross-Site Scripting (XSS):** Sanitize user input before displaying it in the UI. Svelte automatically escapes HTML entities, but be careful when using `@html` or `{@debug}`.
|
||||
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
|
||||
- **SQL Injection:** If interacting with a database, use parameterized queries to prevent SQL injection attacks.
|
||||
- **Input Validation:**
|
||||
- Validate user input on both the client-side and server-side.
|
||||
- Use appropriate data types and validation rules to prevent invalid data from being processed.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use secure authentication mechanisms like OAuth or JWT.
|
||||
- Implement proper authorization checks to ensure that users only have access to the resources they are allowed to access.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms for storing sensitive data.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Validate API responses to ensure that they are valid and not malicious.
|
||||
|
||||
## 5. Testing Approaches:
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Use a testing framework like Jest or Mocha to write unit tests for individual components and utility functions.
|
||||
- Mock external dependencies to isolate the code being tested.
|
||||
- **Integration Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write integration tests that verify the interaction between different components or modules.
|
||||
- Test the integration with APIs and other external services.
|
||||
- **End-to-End Testing:**
|
||||
- Use a testing framework like Cypress or Playwright to write end-to-end tests that simulate user interactions with the application.
|
||||
- Test the entire application flow from start to finish.
|
||||
- **Test Organization:**
|
||||
- Organize tests into directories that mirror the application's directory structure.
|
||||
- Use descriptive names for test files and test cases.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking libraries like Jest's `jest.fn()` or Sinon.js to mock external dependencies.
|
||||
- Use stubbing to replace complex or slow dependencies with simpler implementations for testing purposes.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas:
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect reactivity usage:** Failing to understand how Svelte's reactivity system works can lead to unexpected behavior.
|
||||
- **Over-reliance on `$: `:** Although reactive declarations are powerful, overusing them can make code harder to read and debug. Consider if a regular variable or function would be more appropriate.
|
||||
- **Mutating props directly:** Modifying props directly inside a component can lead to unexpected side effects.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Transition and animation behavior:** Understanding how transitions and animations interact with component updates is important for creating smooth user experiences.
|
||||
- **Server-side rendering (SSR) considerations:** When using SvelteKit, be aware of the differences between client-side and server-side execution environments.
|
||||
- **Version-Specific Issues:**
|
||||
- Consult the Svelte changelog and migration guides when upgrading to a new version to avoid compatibility issues.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that your code is compatible with the target browsers and devices.
|
||||
- Use polyfills or transpilers to support older browsers if necessary.
|
||||
- **Debugging Strategies:**
|
||||
- Use the Svelte Devtools browser extension for inspecting component state and reactivity.
|
||||
- Use `console.log` or the `debugger` statement to debug code execution.
|
||||
- Use SvelteKit's built-in error handling and logging features.
|
||||
|
||||
## 7. Tooling and Environment:
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code with the Svelte extension:** Provides syntax highlighting, code completion, and other useful features.
|
||||
- **Svelte Devtools:** A browser extension for inspecting Svelte component state and reactivity.
|
||||
- **ESLint and Prettier:** For linting and formatting code.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Vite or Rollup to bundle your Svelte code for production.
|
||||
- Configure the build tool to perform optimizations like minification and tree shaking.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with the `eslint-plugin-svelte3` plugin to lint your Svelte code.
|
||||
- Use Prettier with the `prettier-plugin-svelte` plugin to format your Svelte code.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy your Svelte application to a CDN or a serverless platform like Netlify or Vercel.
|
||||
- Configure your server to serve the application's static assets with proper caching headers.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD platform like GitHub Actions or GitLab CI to automate the build, testing, and deployment process.
|
||||
- Run tests and linting checks on every commit to ensure code quality.
|
||||
@@ -0,0 +1,306 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices and coding standards for SvelteKit development, covering code structure, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project health.
|
||||
globs: **/*.svelte
|
||||
---
|
||||
# SvelteKit Best Practices
|
||||
|
||||
This guide provides comprehensive best practices for developing SvelteKit applications. It covers various aspects, including code organization, performance considerations, security measures, and common pitfalls to avoid.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1. Directory Structure Best Practices
|
||||
|
||||
* **`src/lib`**: Reusable components, utilities, and stores. Organize by feature or domain.
|
||||
* **`src/routes`**: Defines the application's routes. Each directory represents a route segment.
|
||||
* **`src/routes/+page.svelte`**: Represents a page component for a route.
|
||||
* **`src/routes/+layout.svelte`**: Layout component that wraps the page. Useful for consistent UI elements.
|
||||
* **`src/routes/+page.server.ts`**: Server-side code for handling data fetching and form submissions for a page.
|
||||
* **`src/routes/+layout.server.ts`**: Server-side code for layout data, loaded before any +page.server.ts data.
|
||||
* **`src/hooks.server.ts`**: Handle server-side requests and responses. Useful for authentication and session management.
|
||||
* **`static`**: Static assets like images, fonts, and other files served directly.
|
||||
* **`tests`**: Directory for all tests, mirroring the source structure for clarity.
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
src/
|
||||
├── lib/
|
||||
│ ├── components/
|
||||
│ │ ├── Button.svelte
|
||||
│ │ └── Card.svelte
|
||||
│ ├── utils/
|
||||
│ │ ├── api.ts
|
||||
│ │ └── helpers.ts
|
||||
│ └── stores/
|
||||
│ └── user.ts
|
||||
├── routes/
|
||||
│ ├── +
|
||||
│ │ └── page.svelte
|
||||
│ ├── about/
|
||||
│ │ ├── +
|
||||
│ │ │ └── page.svelte
|
||||
│ │ └── +page.server.ts
|
||||
│ └── blog/
|
||||
│ ├── [slug]/
|
||||
│ │ ├── +
|
||||
│ │ │ └── page.svelte
|
||||
│ │ └── +page.server.ts
|
||||
│ └── +
|
||||
│ └── page.svelte
|
||||
├── hooks.server.ts
|
||||
└── app.d.ts
|
||||
|
||||
|
||||
### 1.2. File Naming Conventions
|
||||
|
||||
* **Components**: PascalCase (e.g., `MyComponent.svelte`).
|
||||
* **Utility functions**: camelCase (e.g., `formatDate.ts`).
|
||||
* **Stores**: camelCase (e.g., `userStore.ts`).
|
||||
* **Route files**: Follow SvelteKit's routing conventions (`+page.svelte`, `+layout.svelte`, etc.).
|
||||
|
||||
### 1.3. Module Organization
|
||||
|
||||
* Group related functionality into modules.
|
||||
* Use `src/lib` for reusable modules.
|
||||
* Employ clear and descriptive module names.
|
||||
* Leverage SvelteKit's `$lib` alias for importing modules from `src/lib`.
|
||||
|
||||
### 1.4. Component Architecture
|
||||
|
||||
* **Atomic Design**: Break down UI into small, reusable components (atoms, molecules, organisms, templates, pages).
|
||||
* **Component Composition**: Compose complex UIs from simpler components.
|
||||
* **Props and Events**: Use props for data input and events for component output.
|
||||
* **Slots**: Allow parent components to inject content into child components.
|
||||
|
||||
### 1.5. Code Splitting Strategies
|
||||
|
||||
* **Dynamic Imports**: Use dynamic imports (`import()`) to load modules on demand.
|
||||
* **Route-Based Splitting**: SvelteKit automatically splits code based on routes.
|
||||
* **Component-Level Splitting**: Split large components into smaller chunks that can be loaded independently.
|
||||
* **Lazy Loading**: Load non-critical components or modules only when needed.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1. Design Patterns Specific to SvelteKit
|
||||
|
||||
* **Form Actions**: Use SvelteKit's form actions for handling form submissions on the server.
|
||||
* **Load Functions**: Utilize `load` functions in `+page.server.ts` and `+layout.server.ts` for data fetching.
|
||||
* **Stores for State Management**: Employ Svelte stores for managing application state.
|
||||
* **Server-Side Rendering (SSR)**: Leverage SSR for improved SEO and initial load performance.
|
||||
* **Progressive Enhancement**: Design applications to work even with JavaScript disabled.
|
||||
|
||||
### 2.2. Recommended Approaches for Common Tasks
|
||||
|
||||
* **Data Fetching**: Use `fetch` API or libraries like `axios` within `load` functions.
|
||||
* **Form Handling**: Use SvelteKit's form actions for server-side validation and processing.
|
||||
* **Authentication**: Implement authentication using libraries like `lucia-auth` or integrate with OAuth providers.
|
||||
* **Authorization**: Implement role-based access control using stores or server-side checks.
|
||||
* **Error Handling**: Use `try...catch` blocks and SvelteKit's `handleError` hook for global error handling.
|
||||
|
||||
### 2.3. Anti-patterns and Code Smells to Avoid
|
||||
|
||||
* **Over-reliance on Global State**: Avoid using global stores for component-specific state.
|
||||
* **Direct DOM Manipulation**: Avoid directly manipulating the DOM; use Svelte's reactivity system instead.
|
||||
* **Large, Unmaintainable Components**: Break down large components into smaller, reusable ones.
|
||||
* **Ignoring Accessibility**: Ensure components are accessible to users with disabilities (ARIA attributes, semantic HTML).
|
||||
* **Unnecessary Re-renders**: Optimize components to avoid unnecessary re-renders.
|
||||
|
||||
### 2.4. State Management Best Practices
|
||||
|
||||
* **Use Svelte Stores**: Svelte stores are the recommended way to manage application state.
|
||||
* **Divide stores according to feature**: Split stores based on logical domain or feature (e.g. UserStore, CartStore).
|
||||
* **Readable and Writable Stores**: Use readable stores for derived state and writable stores for mutable state.
|
||||
* **Custom Stores**: Create custom stores for complex state management logic.
|
||||
|
||||
### 2.5. Error Handling Patterns
|
||||
|
||||
* **`try...catch` Blocks**: Use `try...catch` blocks to handle errors within components and functions.
|
||||
* **`handleError` Hook**: Implement the `handleError` hook in `src/hooks.server.ts` for global error handling.
|
||||
* **Error Boundaries**: Use error boundaries to catch errors in component trees and display fallback UI.
|
||||
* **Logging**: Log errors to a server for monitoring and debugging.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1. Optimization Techniques
|
||||
|
||||
* **Lazy Loading**: Load non-critical resources (images, components) only when needed.
|
||||
* **Code Splitting**: Split code into smaller chunks to reduce initial load time.
|
||||
* **Image Optimization**: Optimize images using tools like `squoosh` or `tinypng`.
|
||||
* **Server-Side Rendering (SSR)**: Use SSR for improved initial load performance and SEO.
|
||||
* **Caching**: Implement caching strategies for data and assets.
|
||||
* **Preload critical assets**: use `<link rel='preload'>` to fetch critical assets earlier
|
||||
|
||||
### 3.2. Memory Management
|
||||
|
||||
* **Avoid Memory Leaks**: Properly clean up resources when components unmount.
|
||||
* **Use WeakRefs**: Use `WeakRefs` for managing objects that might be garbage collected.
|
||||
* **Minimize Object Creation**: Avoid creating unnecessary objects and arrays.
|
||||
* **Properly unsubscrive from stores:** Properly unsubscribe to avoid re-renders when the component is unmounted.
|
||||
|
||||
### 3.3. Rendering Optimization
|
||||
|
||||
* **Tracked values**: Use the `$:` syntax to track dependencies of reactive statements.
|
||||
* **Svelte Compiler**: Utilize Svelte's compiler to optimize component rendering.
|
||||
* **Virtual DOM**: Svelte doesn't use a virtual DOM, so updates are generally very efficient.
|
||||
* **Avoid Unnecessary Re-renders**: Use `{#each}` blocks with keys to optimize list rendering.
|
||||
* **Debouncing and Throttling**: Use debouncing and throttling to limit the frequency of updates.
|
||||
|
||||
### 3.4. Bundle Size Optimization
|
||||
|
||||
* **Tree Shaking**: Ensure unused code is removed during the build process.
|
||||
* **Minification**: Minify JavaScript and CSS files to reduce bundle size.
|
||||
* **Compression**: Compress assets using gzip or Brotli.
|
||||
* **Dependency Analysis**: Analyze dependencies to identify and remove unused libraries.
|
||||
|
||||
### 3.5. Lazy Loading Strategies
|
||||
|
||||
* **Intersection Observer**: Use the Intersection Observer API to detect when elements are visible and load them lazily.
|
||||
* **Dynamic Imports**: Use dynamic imports to load components and modules on demand.
|
||||
* **Placeholder UI**: Display a placeholder UI while resources are loading.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1. Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
* **Cross-Site Scripting (XSS)**: Sanitize user input to prevent XSS attacks.
|
||||
* **Cross-Site Request Forgery (CSRF)**: Use CSRF tokens to protect against CSRF attacks.
|
||||
* **SQL Injection**: Use parameterized queries or ORMs to prevent SQL injection.
|
||||
* **Authentication and Authorization**: Implement secure authentication and authorization mechanisms.
|
||||
* **Insecure Direct Object References (IDOR)**: Implement proper access controls to prevent unauthorized access to resources.
|
||||
|
||||
### 4.2. Input Validation
|
||||
|
||||
* **Server-Side Validation**: Always validate user input on the server.
|
||||
* **Client-Side Validation**: Use client-side validation for immediate feedback, but never rely on it solely.
|
||||
* **Escape User Input**: Escape user input before rendering it in the DOM.
|
||||
* **Use Validation Libraries**: Use libraries like `zod` or `yup` for input validation.
|
||||
|
||||
### 4.3. Authentication and Authorization Patterns
|
||||
|
||||
* **JWT (JSON Web Tokens)**: Use JWTs for authentication and authorization.
|
||||
* **OAuth 2.0**: Integrate with OAuth providers like Google and Facebook for social login.
|
||||
* **Role-Based Access Control (RBAC)**: Implement RBAC to control access to resources based on user roles.
|
||||
* **Multi-Factor Authentication (MFA)**: Implement MFA for enhanced security.
|
||||
|
||||
### 4.4. Data Protection Strategies
|
||||
|
||||
* **Encryption**: Encrypt sensitive data at rest and in transit.
|
||||
* **Hashing**: Hash passwords using strong hashing algorithms like bcrypt or Argon2.
|
||||
* **Data Masking**: Mask sensitive data in logs and reports.
|
||||
* **Regular Security Audits**: Conduct regular security audits to identify and address vulnerabilities.
|
||||
|
||||
### 4.5. Secure API Communication
|
||||
|
||||
* **HTTPS**: Use HTTPS for all API communication.
|
||||
* **API Keys**: Protect API keys and secrets.
|
||||
* **Rate Limiting**: Implement rate limiting to prevent abuse.
|
||||
* **Input Validation**: Always validate input to your APIs.
|
||||
* **Output Encoding**: Always encode output from your API to prevent injection attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1. Unit Testing Strategies
|
||||
|
||||
* **Test Individual Components**: Write unit tests for individual components in isolation.
|
||||
* **Test Utility Functions**: Write unit tests for utility functions and modules.
|
||||
* **Use Mock Data**: Use mock data for testing components and functions.
|
||||
* **Test Edge Cases**: Test edge cases and error conditions.
|
||||
* **Utilize Svelte Testing Library**: Employ `svelte-testing-library` for testing Svelte components.
|
||||
|
||||
### 5.2. Integration Testing
|
||||
|
||||
* **Test Component Interactions**: Write integration tests to ensure components interact correctly.
|
||||
* **Test Data Flow**: Test the flow of data between components and modules.
|
||||
* **Test API Integrations**: Test integrations with APIs and external services.
|
||||
|
||||
### 5.3. End-to-End Testing
|
||||
|
||||
* **Simulate User Interactions**: Write end-to-end tests to simulate user interactions.
|
||||
* **Test Full Workflows**: Test complete user workflows from start to finish.
|
||||
* **Use Playwright or Cypress**: Use tools like Playwright or Cypress for end-to-end testing.
|
||||
|
||||
### 5.4. Test Organization
|
||||
|
||||
* **Mirror Source Structure**: Organize tests in a directory structure that mirrors the source code.
|
||||
* **Use Descriptive Names**: Use descriptive names for test files and functions.
|
||||
* **Separate Test Environments**: Use separate test environments for unit, integration, and end-to-end tests.
|
||||
|
||||
### 5.5. Mocking and Stubbing
|
||||
|
||||
* **Mock API Calls**: Mock API calls to isolate components during testing.
|
||||
* **Stub External Dependencies**: Stub external dependencies to control their behavior.
|
||||
* **Use Mocking Libraries**: Use libraries like `jest.mock` or `sinon` for mocking and stubbing.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1. Frequent Mistakes Developers Make
|
||||
|
||||
* **Incorrectly Using Reactive Statements**: Not understanding how Svelte's reactivity system works.
|
||||
* **Ignoring Accessibility**: Neglecting accessibility considerations when building components.
|
||||
* **Over-complicating State Management**: Using complex state management solutions when simpler ones would suffice.
|
||||
* **Not Handling Errors Properly**: Ignoring errors or not providing informative error messages.
|
||||
* **Premature Optimization**: Optimizing code before it is necessary.
|
||||
|
||||
### 6.2. Edge Cases to Be Aware Of
|
||||
|
||||
* **Server-Side Rendering Differences**: Be aware of differences between server-side and client-side rendering.
|
||||
* **Browser Compatibility**: Test applications in different browsers to ensure compatibility.
|
||||
* **Network Latency**: Design applications to handle network latency and unreliable connections.
|
||||
* **Memory Constraints**: Consider memory constraints when building large applications.
|
||||
|
||||
### 6.3. Version-Specific Issues
|
||||
|
||||
* **Breaking Changes**: Be aware of breaking changes in new versions of SvelteKit.
|
||||
* **Deprecated Features**: Avoid using deprecated features.
|
||||
* **Upgrade Guides**: Follow upgrade guides when migrating to new versions of SvelteKit.
|
||||
|
||||
### 6.4. Compatibility Concerns
|
||||
|
||||
* **Third-Party Libraries**: Ensure third-party libraries are compatible with SvelteKit.
|
||||
* **Browser Support**: Check browser support for new features and APIs.
|
||||
* **Node.js Version**: Ensure the Node.js version is compatible with SvelteKit.
|
||||
|
||||
### 6.5. Debugging Strategies
|
||||
|
||||
* **Browser Developer Tools**: Use browser developer tools for debugging JavaScript and CSS.
|
||||
* **Svelte Devtools**: Use the Svelte Devtools extension for inspecting Svelte components.
|
||||
* **Logging**: Use `console.log` statements for debugging.
|
||||
* **Debuggers**: Use debuggers like VS Code's debugger for step-by-step debugging.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1. Recommended Development Tools
|
||||
|
||||
* **VS Code**: VS Code is a popular code editor with excellent Svelte and TypeScript support.
|
||||
* **Svelte Devtools**: The Svelte Devtools browser extension allows you to inspect Svelte components.
|
||||
* **ESLint**: ESLint is a linter that helps enforce code style and best practices.
|
||||
* **Prettier**: Prettier is a code formatter that automatically formats code to a consistent style.
|
||||
* **TypeScript**: Using typescript is recommended for type safety.
|
||||
|
||||
### 7.2. Build Configuration
|
||||
|
||||
* **`svelte.config.js`**: Configure SvelteKit using the `svelte.config.js` file.
|
||||
* **Vite**: SvelteKit uses Vite as its build tool.
|
||||
* **Environment Variables**: Use environment variables for configuration settings.
|
||||
* **Adapters**: Use adapters to deploy SvelteKit applications to different environments.
|
||||
|
||||
### 7.3. Linting and Formatting
|
||||
|
||||
* **ESLint**: Configure ESLint to enforce code style and best practices.
|
||||
* **Prettier**: Configure Prettier to automatically format code.
|
||||
* **Husky**: Use Husky to run linters and formatters before committing code.
|
||||
* **Lint Staged**: Use lint-staged to run linters and formatters only on staged files.
|
||||
|
||||
### 7.4. Deployment Best Practices
|
||||
|
||||
* **Choose an Adapter**: Use an adapter like `@sveltejs/adapter-node` or `@sveltejs/adapter-static` to deploy the application.
|
||||
* **Configure Environment Variables**: Configure environment variables for production environments.
|
||||
* **Set Up HTTPS**: Set up HTTPS for secure communication.
|
||||
* **Monitor the Application**: Monitor the application for errors and performance issues.
|
||||
|
||||
### 7.5. CI/CD Integration
|
||||
|
||||
* **Use a CI/CD Pipeline**: Use a CI/CD pipeline to automate the build, test, and deployment process.
|
||||
* **Automated Tests**: Run automated tests in the CI/CD pipeline.
|
||||
* **Automated Deployments**: Automate deployments to production environments.
|
||||
* **Use tools like GitHub Actions, GitLab CI, or CircleCI**
|
||||
Reference in New Issue
Block a user