mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+288
-212
@@ -1,224 +1,300 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices, coding standards, and guidelines for developing applications using Vite, covering aspects from code organization and performance to security and testing.
|
||||
globs: *.js,*.jsx,*.ts,*.tsx,*.vue,*.svelte
|
||||
description: This guide provides definitive best practices for developing high-performance, maintainable applications with Vite, focusing on optimal configuration, code structure, and testing.
|
||||
globs: **/*.{js,jsx}
|
||||
---
|
||||
- **Introduction:**
|
||||
- This document outlines best practices for developing applications using Vite, a fast and opinionated build tool that aims to provide a better development experience.
|
||||
# vite Best Practices
|
||||
|
||||
- **Prerequisites:**
|
||||
- Ensure Node.js and npm/yarn/pnpm are installed.
|
||||
- Familiarity with JavaScript/TypeScript, HTML, and CSS.
|
||||
Vite is the modern standard for frontend tooling. Adhere to these principles to leverage its full potential, ensuring blazing-fast development and optimized production builds.
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Adopt a modular structure based on features or components.
|
||||
|
||||
src/
|
||||
├── components/
|
||||
│ ├── Button/
|
||||
│ │ ├── Button.tsx
|
||||
│ │ ├── Button.module.css
|
||||
│ │ └── Button.test.tsx
|
||||
│ ├── Input/
|
||||
│ │ └── ...
|
||||
├── pages/
|
||||
│ ├── Home.tsx
|
||||
│ ├── About.tsx
|
||||
│ └── ...
|
||||
├── services/
|
||||
│ ├── api.ts
|
||||
│ └── ...
|
||||
├── utils/
|
||||
│ ├── helpers.ts
|
||||
│ └── ...
|
||||
├── App.tsx
|
||||
├── main.tsx
|
||||
└── vite-env.d.ts
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and consistent names.
|
||||
- Component files: `ComponentName.tsx` or `component-name.tsx`.
|
||||
- Style files: `ComponentName.module.css` or `component-name.module.css`.
|
||||
- Test files: `ComponentName.test.tsx` or `component-name.test.tsx`.
|
||||
- **Module Organization:**
|
||||
- Group related files into modules or folders.
|
||||
- Use `index.ts` (barrel files) to simplify imports.
|
||||
typescript
|
||||
// src/components/Button/index.ts
|
||||
export { default as Button } from './Button';
|
||||
|
||||
- **Component Architecture:**
|
||||
- Favor small, reusable components.
|
||||
- Utilize functional components and hooks in React (or equivalent in Vue/Svelte).
|
||||
- Separate concerns: presentational vs. container components.
|
||||
- **Code Splitting Strategies:**
|
||||
- Use dynamic imports (`import()`) for lazy loading.
|
||||
- Split routes using `React.lazy` or Vue's dynamic component feature.
|
||||
- Configure Vite's `rollupOptions.output.manualChunks` for fine-grained control.
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Higher-Order Components (HOCs):** Carefully consider alternatives like render props or hooks for better composability.
|
||||
- **Render Props:** Useful for sharing logic between components, but can lead to deeply nested structures.
|
||||
- **Hooks:** Promote code reuse and simplify component logic.
|
||||
- **Recommended Approaches:**
|
||||
- Use environment variables for configuration.
|
||||
- Implement a consistent API client for data fetching.
|
||||
- Centralize state management using libraries like Redux, Zustand, or Vuex.
|
||||
- **Anti-patterns:**
|
||||
- Avoid deeply nested component trees without proper optimization.
|
||||
- Don't mutate state directly; use setState or Vue's reactivity system.
|
||||
- Overusing global styles; prefer CSS modules or styled components.
|
||||
- **State Management:**
|
||||
- Choose a state management solution based on application complexity.
|
||||
- Use Redux for complex state management with predictable state transitions and time travel debugging.
|
||||
- Consider Zustand or Jotai for simpler state management with a smaller bundle size.
|
||||
- For Vue, Vuex or Pinia are popular choices.
|
||||
- **Error Handling:**
|
||||
- Implement global error boundaries to catch unhandled exceptions.
|
||||
- Use try-catch blocks for local error handling.
|
||||
- Log errors to a central error tracking service (e.g., Sentry, Rollbar).
|
||||
### Keep `vite.config.js` Minimal
|
||||
Vite's philosophy is a lean core. Avoid over-configuring. Only add plugins or options when absolutely necessary.
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use production-ready code minification and bundling.
|
||||
- Optimize images and other assets using tools like `imagemin` or Vite plugins.
|
||||
- **Memory Management:**
|
||||
- Avoid memory leaks by properly cleaning up event listeners and subscriptions.
|
||||
- Use `useEffect` with a cleanup function in React (or `onUnmounted` in Vue).
|
||||
- **Rendering Optimization:**
|
||||
- Use memoization techniques (`React.memo`, `useMemo`, `shouldComponentUpdate`) to prevent unnecessary re-renders.
|
||||
- Virtualize large lists using libraries like `react-window` or `react-virtualized`.
|
||||
- **Bundle Size Optimization:**
|
||||
- Analyze bundle size using `rollup-plugin-visualizer` or similar tools.
|
||||
- Remove unused code using tree shaking.
|
||||
- Use code splitting to load only necessary code.
|
||||
- **Lazy Loading:**
|
||||
- Lazy load components and images that are not immediately visible.
|
||||
- Use `IntersectionObserver` to trigger loading when elements enter the viewport.
|
||||
❌ **BAD** - Overly complex `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import legacy from '@vitejs/plugin-legacy';
|
||||
import { visualizer } from 'rollup-plugin-visualizer';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- Cross-Site Scripting (XSS): Sanitize user input to prevent XSS attacks.
|
||||
- Cross-Site Request Forgery (CSRF): Use CSRF tokens to protect against CSRF attacks.
|
||||
- Injection Attacks: Validate and sanitize input to prevent SQL injection and other injection attacks.
|
||||
- **Input Validation:**
|
||||
- Validate all user input on both the client and server side.
|
||||
- Use a library like `yup` or `joi` for schema validation.
|
||||
- **Authentication and Authorization:**
|
||||
- Use a secure authentication and authorization mechanism (e.g., OAuth 2.0, JWT).
|
||||
- Store passwords securely using bcrypt or Argon2.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS for all communication.
|
||||
- **Secure API Communication:**
|
||||
- Implement proper CORS configuration to prevent unauthorized access to your API.
|
||||
- Rate limit API requests to prevent abuse.
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Write unit tests for individual components and functions.
|
||||
- Use testing libraries like Jest, Mocha, or Vitest.
|
||||
- Mock dependencies to isolate units under test.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different parts of your application.
|
||||
- Use testing libraries like React Testing Library or Vue Test Utils.
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application from the user's perspective.
|
||||
- Use tools like Cypress or Playwright.
|
||||
- **Test Organization:**
|
||||
- Organize tests into folders based on features or components.
|
||||
- Use descriptive test names.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocks and stubs to isolate units under test.
|
||||
- Avoid over-mocking; test the actual implementation whenever possible.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- Improperly handling asynchronous operations.
|
||||
- Neglecting accessibility considerations.
|
||||
- Using outdated dependencies.
|
||||
- **Edge Cases:**
|
||||
- Handling different screen sizes and devices.
|
||||
- Supporting internationalization and localization.
|
||||
- Dealing with slow network connections.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes in Vite and its plugins.
|
||||
- Pin dependencies to specific versions to avoid unexpected issues.
|
||||
- **Compatibility Concerns:**
|
||||
- Test your application in different browsers and devices.
|
||||
- Use polyfills to support older browsers.
|
||||
- **Debugging Strategies:**
|
||||
- Use browser developer tools to inspect the DOM, network requests, and console output.
|
||||
- Use debugging tools like `debugger` or `console.log`.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Recommended Tools:**
|
||||
- VS Code with extensions like ESLint, Prettier, and TypeScript.
|
||||
- Chrome DevTools or Firefox Developer Tools.
|
||||
- npm/yarn/pnpm for package management.
|
||||
- **Build Configuration:**
|
||||
- Configure Vite using `vite.config.ts` or `vite.config.js`.
|
||||
- Customize build options like `outDir`, `assetsDir`, and `rollupOptions`.
|
||||
- **Linting and Formatting:**
|
||||
- Use ESLint with recommended rulesets (e.g., `eslint:recommended`, `plugin:react/recommended`).
|
||||
- Use Prettier for code formatting.
|
||||
- Configure ESLint and Prettier to work together.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy to a CDN for optimal performance.
|
||||
- Use environment variables for configuration.
|
||||
- Set up proper caching headers.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate with a CI/CD pipeline for automated testing and deployment.
|
||||
- Use tools like GitHub Actions, GitLab CI, or CircleCI.
|
||||
|
||||
- **TypeScript Best Practices (when using TypeScript):**
|
||||
- **Strict Type-Checking:**
|
||||
- Enable strict type-checking options in `tsconfig.json` (e.g., `strict: true`, `noImplicitAny: true`, `strictNullChecks: true`).
|
||||
- **Typing Props and State:**
|
||||
- Use interfaces or types to define the shape of props and state.
|
||||
typescript
|
||||
interface ButtonProps {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
|
||||
return <button onClick={onClick}>{label}</button>;
|
||||
};
|
||||
|
||||
|
||||
- **ESLint Configuration (Example):**
|
||||
javascript
|
||||
module.exports = {
|
||||
env: {
|
||||
browser: true,
|
||||
es2021: true,
|
||||
node: true,
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
legacy({ targets: ['defaults', 'not IE 11'] }),
|
||||
visualizer({ filename: './dist/stats.html' }),
|
||||
VitePWA({ registerType: 'autoUpdate' }),
|
||||
// ... many more plugins
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
'~': '/node_modules',
|
||||
},
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:react/recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'prettier',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
|
||||
},
|
||||
build: {
|
||||
target: 'es2015',
|
||||
minify: 'terser',
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
vendor: ['react', 'react-dom'],
|
||||
},
|
||||
},
|
||||
ecmaVersion: 12,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['react', '@typescript-eslint', 'prettier'],
|
||||
rules: {
|
||||
'prettier/prettier': 'error',
|
||||
'react/react-in-jsx-scope': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
open: true,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
};
|
||||
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
- **Conclusion:**
|
||||
- Following these best practices will help you build efficient, maintainable, and secure applications with Vite. Continuously review and update your practices as the library and ecosystem evolve.
|
||||
✅ **GOOD** - Lean and focused `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// Only add resolve.alias if absolutely needed for complex paths.
|
||||
// Avoid resolve.extensions unless you have specific non-standard file types.
|
||||
// Vite's defaults are usually sufficient.
|
||||
});
|
||||
```
|
||||
|
||||
### Use Explicit File Extensions
|
||||
Relying on `resolve.extensions` for implicit imports forces Vite to perform multiple filesystem checks, slowing down resolution. Be explicit.
|
||||
|
||||
❌ **BAD** - Implicit import
|
||||
```javascript
|
||||
// src/components/MyComponent.jsx
|
||||
import { util } from '../utils'; // Vite has to guess .js, .ts, .jsx etc.
|
||||
```
|
||||
|
||||
✅ **GOOD** - Explicit import
|
||||
```javascript
|
||||
// src/components/MyComponent.jsx
|
||||
import { util } from '../utils/index.js'; // Or .ts, .jsx, etc.
|
||||
```
|
||||
|
||||
### Avoid Barrel Files
|
||||
Barrel files (e.g., `index.js` re-exporting many modules) force Vite to fetch and transform all re-exported files, even if only one API is used. This hurts initial page load performance.
|
||||
|
||||
❌ **BAD** - Barrel file (`src/utils/index.js`)
|
||||
```javascript
|
||||
// src/utils/index.js
|
||||
export * from './color.js';
|
||||
export * from './dom.js';
|
||||
export * from './slash.js';
|
||||
|
||||
// src/app.js
|
||||
import { slash } from './utils'; // Loads color.js, dom.js, and slash.js
|
||||
```
|
||||
|
||||
✅ **GOOD** - Direct imports
|
||||
```javascript
|
||||
// src/app.js
|
||||
import { slash } from './utils/slash.js'; // Only loads slash.js
|
||||
```
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### Embrace Native ES Modules
|
||||
Vite is built on native ES Modules. Always write your client-side code using `import`/`export` syntax.
|
||||
|
||||
❌ **BAD** - CommonJS in client-side code
|
||||
```javascript
|
||||
// main.js
|
||||
const myModule = require('./my-module'); // Will fail in browser
|
||||
```
|
||||
|
||||
✅ **GOOD** - Native ES Modules
|
||||
```javascript
|
||||
// main.js
|
||||
import myModule from './my-module.js';
|
||||
```
|
||||
|
||||
### Use `import.meta.env` for Environment Variables
|
||||
Vite injects environment variables via `import.meta.env`. This is the correct way to access them in client-side code. `process.env` is for Node.js environments.
|
||||
|
||||
❌ **BAD** - Using `process.env` in client code
|
||||
```javascript
|
||||
// app.js
|
||||
console.log(process.env.VITE_API_URL); // `process` is not defined in browser
|
||||
```
|
||||
|
||||
✅ **GOOD** - Using `import.meta.env`
|
||||
```javascript
|
||||
// app.js
|
||||
console.log(import.meta.env.VITE_API_URL); // Correctly accesses Vite env vars
|
||||
```
|
||||
|
||||
### Optimize with Dynamic Imports
|
||||
For large components or libraries, use dynamic imports to load them only when needed, reducing initial bundle size and improving load times.
|
||||
|
||||
❌ **BAD** - Eagerly loading large component
|
||||
```javascript
|
||||
// App.jsx
|
||||
import LargeComponent from './LargeComponent'; // Always bundled
|
||||
function App() {
|
||||
return <LargeComponent />;
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD** - Dynamically importing
|
||||
```javascript
|
||||
// App.jsx (React example)
|
||||
import { lazy, Suspense } from 'react';
|
||||
const LargeComponent = lazy(() => import('./LargeComponent'));
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LargeComponent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### Audit Custom Plugins
|
||||
Community plugins can introduce performance bottlenecks. Profile them using Vite's debug flags.
|
||||
|
||||
❌ **BAD** - Blindly adding plugins
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
import someHeavyPlugin from 'some-heavy-plugin'; // No profiling done
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [someHeavyPlugin()],
|
||||
});
|
||||
```
|
||||
|
||||
✅ **GOOD** - Profiling plugins
|
||||
```bash
|
||||
# Run Vite with debug flags to identify slow plugins
|
||||
vite --debug plugin-transform
|
||||
```
|
||||
Use `vite-plugin-inspect` to visualize the transform pipeline.
|
||||
|
||||
### Optimize Browser Setup
|
||||
Browser extensions and disabled cache settings can severely impact dev server performance.
|
||||
|
||||
❌ **BAD** - Developing with "Disable Cache" enabled in dev tools.
|
||||
```
|
||||
// Browser Dev Tools -> Network tab -> "Disable Cache" checked
|
||||
```
|
||||
|
||||
✅ **GOOD** - Use a clean browser profile or incognito mode.
|
||||
Ensure "Disable Cache" is **unchecked** in dev tools.
|
||||
|
||||
### Warm Up Critical Files
|
||||
For complex applications, pre-warming frequently used files can prevent request waterfalls.
|
||||
|
||||
❌ **BAD** - Relying solely on on-demand transformation for critical paths.
|
||||
```javascript
|
||||
// No explicit warmup configured
|
||||
```
|
||||
|
||||
✅ **GOOD** - Use `server.warmup` in `vite.config.js`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
warmup: {
|
||||
clientFiles: ['./src/main.js', './src/App.jsx'],
|
||||
// Or use patterns: ['**/*.vue', '**/*.jsx']
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## 4. Common Pitfalls and Gotchas
|
||||
|
||||
### Incorrect Base Path for Deployment
|
||||
When deploying to a sub-path (e.g., `yourdomain.com/my-app/`), ensure `base` is correctly configured.
|
||||
|
||||
❌ **BAD** - Hardcoding absolute paths or missing `base`
|
||||
```javascript
|
||||
// vite.config.js
|
||||
// Default base: '/'
|
||||
// Assets might break when deployed to a sub-path
|
||||
```
|
||||
|
||||
✅ **GOOD** - Configure `base` for sub-path deployments
|
||||
```javascript
|
||||
// vite.config.js
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
base: '/my-app/', // For deploying to https://yourdomain.com/my-app/
|
||||
// Or use './' for relative paths if the base is unknown at build time
|
||||
// base: './',
|
||||
});
|
||||
```
|
||||
Access the base path in your code via `import.meta.env.BASE_URL`.
|
||||
|
||||
### Mismanaging `NODE_ENV` with API Usage
|
||||
When using Vite's JS API (`createServer`, `build`) in the same Node.js process, ensure `process.env.NODE_ENV` or the `mode` config option is consistent to prevent conflicts.
|
||||
|
||||
❌ **BAD** - Conflicting `NODE_ENV`
|
||||
```javascript
|
||||
// script.js
|
||||
process.env.NODE_ENV = 'production';
|
||||
await createServer(); // Might behave unexpectedly
|
||||
```
|
||||
|
||||
✅ **GOOD** - Explicitly set `mode` or spawn child processes
|
||||
```javascript
|
||||
// script.js
|
||||
import { createServer } from 'vite';
|
||||
// Option 1: Explicitly set mode
|
||||
const devServer = await createServer({ mode: 'development' });
|
||||
await devServer.listen();
|
||||
|
||||
// Option 2: Spawn child processes for separate contexts
|
||||
// (e.g., one for dev server, one for build)
|
||||
```
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### Standardize on Vitest
|
||||
Vitest is the official testing framework for Vite projects, offering seamless integration with Vite's configuration and plugin ecosystem.
|
||||
|
||||
❌ **BAD** - Using a separate test runner (e.g., Jest) that requires its own complex configuration.
|
||||
```json
|
||||
// package.json
|
||||
"scripts": {
|
||||
"test": "jest" // Requires separate Babel/Webpack config
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD** - Integrate Vitest directly into `vite.config.ts`
|
||||
```typescript
|
||||
// vite.config.ts
|
||||
/// <reference types="vitest/config" />
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
test: {
|
||||
globals: true, // For global APIs like `describe`, `it`, `expect`
|
||||
environment: 'jsdom', // Or 'node'
|
||||
setupFiles: './src/setupTests.js', // Global setup for tests
|
||||
},
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user