# Deployment and DevOps Standards for TypeScript
This document outlines the standards and best practices for deployment and DevOps when developing applications with TypeScript. These guidelines are designed to ensure consistency, maintainability, performance, and security across the development lifecycle, from build processes to production deployment.
## 1. Build Processes and Tooling
### 1.1. Transpilation and Bundling
**Standard:** Use a modern build tool like esbuild, swc, or Parcel for faster transpilation and bundling. Favor tools configured through code rather than relying solely on CLI arguments. This provides better maintainability and readability.
**Why:** Efficient build processes are critical for rapid development cycles and fast deployment times. Modern tools significantly outperform older solutions like "tsc" alone or Webpack with complex configurations.
**Do This:**
"""typescript
// esbuild-config.ts
import { build } from 'esbuild';
build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js',
platform: 'node', // or 'browser'
format: 'cjs', // or 'esm'
minify: true,
sourcemap: true,
}).catch(() => process.exit(1));
"""
**Don't Do This:**
"""bash
# Avoid complex and unmaintainable CLI commands
tsc src/index.ts --module commonjs --target esnext --outDir dist
"""
**Anti-Pattern:** Relying on global installations of build tools. Use "npm" or "yarn" scripts that reference local "node_modules" binaries.
### 1.2. Package Management
**Standard:** Use "npm", "yarn", or "pnpm" for package management. Prefer "pnpm" for monorepos and enhanced disk space efficiency. Utilize semantic versioning (semver) and lockfiles ("package-lock.json", "yarn.lock", "pnpm-lock.yaml").
**Why:** Ensures reproducible builds and prevents unexpected breaking changes due to dependency updates.
**Do This:**
* Always commit lockfiles to version control.
* Use "npm ci", "yarn install --frozen-lockfile", or "pnpm install --frozen-lockfile" in CI/CD environments to ensure the exact versions specified in the lockfile are installed.
**Don't Do This:**
* Installing dependencies without a lockfile.
* Ignoring semver ranges and always using "latest" versions. This can lead to unpredictable behavior.
**Code Example:**
"""json
// package.json
{
"name": "my-typescript-app",
"version": "1.0.0",
"dependencies": {
"axios": "^1.6.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"typescript": "^5.0",
"esbuild": "^0.19"
},
"scripts": {
"build": "node esbuild-config.ts",
"start": "node dist/bundle.js",
"ci": "npm ci" // or yarn install --frozen-lockfile or pnpm install --frozen-lockfile
}
}
"""
### 1.3. Linting and Formatting
**Standard:** Integrate ESLint with TypeScript support, Prettier, and potentially Stylelint (if using CSS/SCSS). Use a shared configuration (".eslintrc.js", ".prettierrc.js") across the team. Add linting and formatting as pre-commit hooks using Husky and lint-staged.
**Why:** Enforces consistent code style, catches potential errors early, and improves code readability.
**Do This:**
"""javascript
// .eslintrc.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
project: './tsconfig.json',
},
plugins: ['@typescript-eslint', 'prettier'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
rules: {
'prettier/prettier': 'error',
'@typescript-eslint/explicit-function-return-type': 'warn',
'@typescript-eslint/no-explicit-any': 'off',
// Add custom rules as needed
},
};
"""
"""json
// .prettierrc.js
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 2,
};
"""
**Don't Do This:**
* Ignoring linting warnings or errors.
* Allowing inconsistent formatting across the codebase.
**Anti-Pattern:** Relying on manual linting and formatting. Automate the process with pre-commit hooks.
### 1.4. Type Checking
**Standard:** Enable strict type checking ("strict: true") in "tsconfig.json". Address all type errors and warnings. Use TypeScript's advanced type features (e.g., generics, conditional types, mapped types) to improve type safety.
**Why:** TypeScript's strong typing is its primary strength. Strict type checking catches errors at compile time that would otherwise surface at runtime.
**Do This:**
"""json
// tsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "dist" ,
// other options
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
"""
**Don't Do This:**
* Disabling strict type checking.
* Using "any" excessively. Use more specific types whenever possible. When "any" is unavoidable, document the reason.
## 2. CI/CD Pipelines
### 2.1. Pipeline Stages
**Standard:** Implement a CI/CD pipeline with stages for:
* **Linting and Formatting:** Run ESLint and Prettier. Fail the build if violations are found.
* **Type Checking:** Run "tsc --noEmit" to check for type errors without emitting JavaScript.
* **Unit Testing:** Run unit tests with a coverage threshold.
* **Build:** Transpile and bundle the code.
* **Integration Testing:** Run integration tests against a staging environment (if applicable).
* **Deployment:** Deploy to production or staging environments.
**Why:** Automated pipelines ensure consistent code quality, prevent regressions, and streamline the deployment process.
**Code Example (GitHub Actions):**
"""yaml
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: 20
- run: npm ci
- run: npm run lint
- run: npm run typecheck # tsc --noEmit
- run: npm run test:unit -- --coverage
env:
CI: true # Ensure proper jest exit code
- run: npm run build
- name: Upload Artifact
if: github.ref == 'refs/heads/main'
uses: actions/upload-artifact@v3
with:
name: dist
path: dist
"""
**Anti-Pattern:** Manual deployments and testing.
### 2.2. Environment Variables
**Standard:** Manage configuration using environment variables, secrets management tools (e.g., HashiCorp Vault, AWS Secrets Manager, Doppler), and configuration files. Avoid hardcoding sensitive information in the codebase.
**Why:** Separates configuration from code, making it easier to deploy to different environments and protecting sensitive data.
**Do This:**
"""typescript
// config.ts
const API_URL = process.env.API_URL || 'http://localhost:3000';
const SECRET_KEY = process.env.SECRET_KEY;
if (!SECRET_KEY) {
console.error('SECRET_KEY is not defined in environment variables!');
process.exit(1);
}
export const config = {
apiUrl: API_URL,
secretKey: SECRET_KEY,
};
"""
**Don't Do This:**
"""typescript
// Anti-pattern: Hardcoding sensitive information
const config = {
apiUrl: 'http://localhost:3000',
secretKey: 'my_secret_key', // DO NOT DO THIS!
};
"""
**Technology-Specific Details:**
* **Serverless Functions (e.g., AWS Lambda, Azure Functions):** Utilize the platform's built-in environment variable management.
* **Docker:** Pass environment variables to containers using the "-e" flag or a ".env" file (for local development only; never commit ".env" files with secrets!).
### 2.3. Versioning and Tagging
**Standard:** Use semantic versioning (semver) for releases. Tag releases in Git. Automate version bumping using tools like "standard-version" or "semantic-release".
**Why:** Provides a clear and consistent way to track changes and manage dependencies.
**Do This:**
* Use "standard-version" to automatically bump the version number, generate changelogs, and tag releases based on commit messages.
* Follow conventional commits.
### 2.4. Infrastructure as Code (IaC)
**Standard:** Define infrastructure using IaC tools like Terraform, Pulumi, or AWS CloudFormation.
**Why:** Allows for automated provisioning and management of infrastructure, ensuring consistency and reproducibility.
**Code Example (Terraform):**
"""terraform
# main.tf
resource "aws_instance" "example" {
ami = "ami-0c55b9a4c55bb3f16" # Example AMI
instance_type = "t2.micro"
tags = {
Name = "my-typescript-app"
}
}
"""
## 3. Production Considerations
### 3.1. Monitoring and Logging
**Standard:** Implement comprehensive monitoring (e.g., Prometheus, Grafana, Datadog) and logging (e.g., Winston, Bunyan, Pino) for production applications. Use structured logging (e.g., JSON) for easier analysis.
**Why:** Provides visibility into application health, performance, and errors, enabling proactive issue resolution.
**Do This:**
"""typescript
// logger.ts (using Pino)
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
formatters: {
level: (label) => {
return { level: label };
},
},
timestamp: pino.stdTimeFunctions.isoTime,
});
export default logger;
"""
"""typescript
// Example Usage
import logger from './logger';
try {
// ... some code
} catch (error) {
logger.error({ error }, 'An error occurred');
}
"""
**Don't Do This:**
* Relying solely on "console.log" in production.
* Logging sensitive information (e.g., passwords, API keys).
### 3.2. Security
**Standard:** Follow security best practices for TypeScript applications, including:
* **Input Validation:** Validate all user input to prevent injection attacks.
* **Output Encoding:** Encode output to prevent cross-site scripting (XSS) attacks.
* **Authentication and Authorization:** Implement robust authentication and authorization mechanisms.
* **Dependency Scanning:** Regularly scan dependencies for vulnerabilities using tools like "npm audit" or "yarn audit". Consider using automated dependency update tools (e.g., Dependabot).
* **Secrets Management:** Store and manage secrets securely (see section 2.2).
* **Regular Security Audits:** Conduct regular security audits to identify and address vulnerabilities.
**Why:** Protects the application and its users from security threats.
**Technology-Specific Details:**
* **OWASP Top 10:** Familiarize yourself with the OWASP Top 10 web application security risks and how to mitigate them in TypeScript applications.
### 3.3. Performance Optimization
**Standard:** Optimize TypeScript applications for performance by:
* **Code Splitting:** Break up large bundles into smaller chunks that can be loaded on demand. (Especially important for web applications)
* **Lazy Loading:** Load resources only when they are needed.
* **Caching:** Implement caching strategies to reduce server load and improve response times.
* **Profiling:** Use profiling tools to identify performance bottlenecks. Analyze the generated JavaScript to ensure it is efficient.
* **Using the latest Typescript Compiler Options** : target esnext.
**Why:** Ensures a fast and responsive user experience.
**Technology-Specific Details:**
* **Node.js:** Utilize Node.js profiling tools to identify performance bottlenecks.
### 3.4. Zero Downtime Deployment
**Standard:** Implement strategies for zero downtime deployment, such as:
* **Blue/Green Deployments:** Deploy the new version of the application to a separate environment (the "green" environment) and then switch traffic to it.
* **Rolling Updates:** Gradually update instances of the application one at a time.
**Why:** Minimizes disruption to users during deployments.
### 3.5. Rollbacks
**Standard:** Establish a clear rollback strategy. If a deployment causes issues, be able to quickly revert to the previous stable version.
**Why:** Minimizes impact of faulty deployments.
This document provides a comprehensive overview of deployment and DevOps standards for TypeScript. Adhering to these guidelines will help ensure the development of high-quality, maintainable, and secure TypeScript applications.
danielsogl
Created Mar 6, 2025
This guide explains how to effectively use .clinerules
with Cline, the AI-powered coding assistant.
The .clinerules
file is a powerful configuration file that helps Cline understand your project's requirements, coding standards, and constraints. When placed in your project's root directory, it automatically guides Cline's behavior and ensures consistency across your codebase.
Place the .clinerules
file in your project's root directory. Cline automatically detects and follows these rules for all files within the project.
# Project Overview project: name: 'Your Project Name' description: 'Brief project description' stack: - technology: 'Framework/Language' version: 'X.Y.Z' - technology: 'Database' version: 'X.Y.Z'
# Code Standards standards: style: - 'Use consistent indentation (2 spaces)' - 'Follow language-specific naming conventions' documentation: - 'Include JSDoc comments for all functions' - 'Maintain up-to-date README files' testing: - 'Write unit tests for all new features' - 'Maintain minimum 80% code coverage'
# Security Guidelines security: authentication: - 'Implement proper token validation' - 'Use environment variables for secrets' dataProtection: - 'Sanitize all user inputs' - 'Implement proper error handling'
Be Specific
Maintain Organization
Regular Updates
# Common Patterns Example patterns: components: - pattern: 'Use functional components by default' - pattern: 'Implement error boundaries for component trees' stateManagement: - pattern: 'Use React Query for server state' - pattern: 'Implement proper loading states'
Commit the Rules
.clinerules
in version controlTeam Collaboration
Rules Not Being Applied
Conflicting Rules
Performance Considerations
# Basic .clinerules Example project: name: 'Web Application' type: 'Next.js Frontend' standards: - 'Use TypeScript for all new code' - 'Follow React best practices' - 'Implement proper error handling' testing: unit: - 'Jest for unit tests' - 'React Testing Library for components' e2e: - 'Cypress for end-to-end testing' documentation: required: - 'README.md in each major directory' - 'JSDoc comments for public APIs' - 'Changelog updates for all changes'
# Advanced .clinerules Example project: name: 'Enterprise Application' compliance: - 'GDPR requirements' - 'WCAG 2.1 AA accessibility' architecture: patterns: - 'Clean Architecture principles' - 'Domain-Driven Design concepts' security: requirements: - 'OAuth 2.0 authentication' - 'Rate limiting on all APIs' - 'Input validation with Zod'
# TypeScript Performance Optimization Standards: Best Practices for Efficient Applications This document outlines coding standards and best practices specifically for performance optimization in TypeScript projects. Adhering to these guidelines will improve the speed, responsiveness, efficient use of resources, and overall user experience of your applications. ## Table of Contents - [1. Architectural Considerations for Performance](#1-architectural-considerations-for-performance) - [1.1. Code Splitting](#11-code-splitting) - [1.2. Lazy Loading Modules](#12-lazy-loading-modules) - [1.3. Server-Side Rendering (SSR) or Static Site Generation (SSG)](#13-server-side-rendering-ssr-or-static-site-generation-ssg) - [1.4. Data Structure Selection](#14-data-structure-selection) ## 1. Architectural Considerations for Performance ### 1.1. Code Splitting **Standard:** Implement code splitting to reduce the initial load time of your application. **Why:** Loading only the necessary code on initial page load significantly improves the user experience. **Do This:** * Utilize dynamic imports (`import()`) to load modules on demand. * Configure your bundler (Webpack, Parcel, Rollup) to create separate chunks for different parts of your application. **Don't Do This:** * Load the entire application code in a single bundle. * Use `require()` statements (CommonJS) in modern TypeScript projects where ES Modules are supported. **Example:** ```typescript // Before: Loading everything upfront import { featureA } from './featureA'; import { featureB } from './featureB'; // After: Code splitting with dynamic imports async function loadFeatureA() { const { featureA } = await import('./featureA'); featureA.init(); } async function loadFeatureB() { const { featureB } = await import('./featureB'); featureB.init(); } // Use loadFeatureA or loadFeatureB based on user interaction or route ``` **Bundler Configuration (Webpack example):** ```javascript // webpack.config.js module.exports = { entry: './src/index.ts', output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, optimization: { splitChunks: { chunks: 'all', // Split all chunks of code }, }, }; ``` ### 1.2. Lazy Loading Modules **Standard:** Employ lazy loading for non-critical modules or components. **Why:** Reduce the amount of code that needs to be parsed and compiled on initial load. **Do This:** * Load components or modules only when they are needed. * Utilize Intersection Observer API to load components when they become visible in the viewport. **Don't Do This:** * Load modules that are not immediately required for the current user interaction. **Example (Intersection Observer Lazy Loading):** ```typescript function lazyLoadComponent(element: HTMLElement, importPath: string) { const observer = new IntersectionObserver((entries) => { entries.forEach(async (entry) => { if (entry.isIntersecting) { const { default: Component } = await import(importPath); const componentInstance = new Component(); // Instantiate the component. element.appendChild(componentInstance.render()); // Append to the DOM (adjust according to your framework). observer.unobserve(element); } }); }); observer.observe(element); } // Usage: const lazyComponentElement = document.getElementById('lazy-component'); if (lazyComponentElement) { lazyLoadComponent(lazyComponentElement, './MyHeavyComponent'); } ``` ### 1.3. Server-Side Rendering (SSR) or Static Site Generation (SSG) **Standard:** Consider using SSR or SSG for content-heavy, SEO-sensitive, or performance-critical applications. **Why:** Reduces the time to first paint (TTFP) and improves SEO by providing crawlers with pre-rendered content. **Do This:** * Evaluate the trade-offs between SSR, SSG, and client-side rendering (CSR) based on your application's needs. * Use frameworks like Next.js (React), Nuxt.js (Vue), or Angular Universal. * Implement appropriate caching strategies for SSR. **Don't Do This:** * Default to CSR when SSR or SSG could provide significant performance benefits. **Example (Next.js):** ```typescript // pages/index.tsx (Next.js example) import React from 'react'; interface Props { data: { title: string; description: string; }; } const HomePage: React.FC<Props> = ({ data }) => { return ( <div> <h1>{data.title}</h1> <p>{data.description}</p> </div> ); }; export async function getServerSideProps() { // Fetch data from an API, database, or file system. const data = { title: 'My Awesome Website', description: 'Welcome to my extremely performant website!', }; return { props: { data, }, }; } export default HomePage; ``` ### 1.4. Data Structure Selection **Standard:** Select the most appropriate data structure for each specific use case. **Why:** Using appropriate data structures will reduce the complexity and improve the execution speed of algorithms. **Do This:** * Use `Map` when you need to associate keys with values, especially when the keys are not strings or numbers. * Use `Set` when you need to store a collection of unique values. * Use `Record<K, V>` type for type-safe object mapping. * Consider specialized data structures for specific performance needs (e.g., priority queues, linked lists). **Don't Do This:** * Use generic arrays or objects when more specialized data structures would be more efficient. * Perform frequent lookups in arrays when using a Map or Set would be more performant. **Example:** ```typescript // Before: Using an array for lookups const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; // O(n) lookup operation const findUser = (id: number) => users.find(user => user.id === id); // After: Using Map for efficient lookups const userMap = new Map<number, {id: number, name: string}>(); userMap.set(1, { id: 1, name: 'Alice' }); userMap.set(2, { id: 2, name: 'Bob' }); userMap.set(3, { id: 3, name: 'Charlie' }); // O(1) lookup operation const getUser = (id: number) => userMap.get(id); ```
Debe preferir usar el gestor de versiones "pnpm" por sobre "npm" para la ejecución de los comandos.
# Storybook Guidelines for Angular (v9.0.18+) Use these guidelines when working with Storybook in Angular projects. This document covers modern patterns, best practices, and the latest features in Storybook 9.x. ## 1. Core Architecture & Setup ### Framework Configuration - **Angular Framework**: Always use `@storybook/angular` as the framework in your `.storybook/main.ts` - **TypeScript First**: All configuration files should use TypeScript (`.ts` extension) - **Standalone Components**: Leverage Angular standalone components in stories - they work seamlessly with Storybook - **Modern Angular Patterns**: Support for Angular 17+ features including signals, control flow, and standalone APIs ### Basic Configuration Structure ```typescript // .storybook/main.ts import type { StorybookConfig } from '@storybook/angular'; const config: StorybookConfig = { framework: { name: '@storybook/angular', options: { // Framework-specific options }, }, stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], addons: [ '@storybook/addon-essentials', '@storybook/addon-interactions', '@storybook/addon-a11y', '@storybook/addon-docs', '@storybook/addon-vitest', // For Storybook 9.x testing ], }; export default config; ``` ## 2. Story Structure & CSF 3 Patterns ### Modern Story Format (CSF 3) - **Component Story Format 3**: Use the latest CSF 3 syntax for all new stories - **TypeScript Types**: Always use `Meta` and `StoryObj` for type safety - **Minimal Boilerplate**: Leverage CSF 3's simplified syntax ```typescript import type { Meta, StoryObj } from '@storybook/angular'; import { Button } from './button.component'; const meta: Meta = { component: Button, }; export default meta; type Story = StoryObj; export const Primary: Story = { args: { primary: true, label: 'Button', }, }; export const Secondary: Story = { args: { primary: false, label: 'Button', }, }; ``` ### Story Naming & Organization - **Descriptive Names**: Use clear, descriptive names for story exports - **Hierarchical Titles**: Organize stories with meaningful hierarchies using forward slashes - **Auto-Generated Titles**: Leverage automatic title generation when possible - **Component-Centric**: Group stories by component, not by state ```typescript const meta: Meta = { title: 'Design System/Components/Button', // Hierarchical organization component: Button, }; ``` ## 3. Angular-Specific Patterns ### Standalone Components (Recommended) - **Default Approach**: Prefer standalone components for new development - **No Module Imports**: Avoid importing CommonModule or other NgModules - **Direct Dependencies**: Import only required standalone components, directives, or pipes ```typescript // ✅ Good - Standalone component story import type { Meta, StoryObj } from '@storybook/angular'; import { MyStandaloneComponent } from './my-standalone.component'; const meta: Meta = { component: MyStandaloneComponent, }; ``` ### Legacy Module-Based Components - **Module Metadata**: Use `moduleMetadata` decorator for components requiring NgModules - **Minimal Imports**: Import only necessary modules and declarations ```typescript // For legacy components requiring modules import { moduleMetadata } from '@storybook/angular'; import { CommonModule } from '@angular/common'; const meta: Meta = { component: LegacyComponent, decorators: [ moduleMetadata({ imports: [CommonModule], declarations: [LegacyComponent, ChildComponent], }), ], }; ``` ### Application Configuration - **Provider Setup**: Use `applicationConfig` decorator for dependency injection - **Service Mocking**: Configure providers for testing scenarios ```typescript import { applicationConfig } from '@storybook/angular'; import { importProvidersFrom } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; const meta: Meta = { component: MyComponent, decorators: [ applicationConfig({ providers: [ importProvidersFrom(BrowserAnimationsModule), // Add other providers as needed ], }), ], }; ``` ## 4. Story Configuration & Best Practices ### Args and Controls - **Typed Args**: Leverage TypeScript for type-safe arguments - **Meaningful Defaults**: Provide sensible default values - **Control Types**: Explicitly define control types when needed ```typescript const meta: Meta = { component: Button, argTypes: { size: { control: { type: 'select' }, options: ['small', 'medium', 'large'], }, disabled: { control: { type: 'boolean' }, }, }, args: { // Default args for all stories size: 'medium', disabled: false, label: 'Button', }, }; ``` ### Parameters Configuration - **Global Parameters**: Set common parameters at the meta level - **Story-Specific Overrides**: Override parameters for specific stories when needed - **Documentation**: Use parameters for docs configuration ```typescript const meta: Meta = { component: Button, parameters: { docs: { description: { component: 'A versatile button component for user interactions.', }, }, backgrounds: { default: 'light', }, }, }; export const OnDark: Story = { parameters: { backgrounds: { default: 'dark' }, }, }; ``` ## 5. Advanced Patterns ### Custom Render Functions - **Complex Templates**: Use render functions for complex component templates - **Template Customization**: Provide custom templates when component alone isn't sufficient ```typescript export const WithCustomTemplate: Story = { render: args => ({ props: args, template: ` <p>Additional content around the button</p> `, }), }; ``` ### Component Composition - **Multi-Component Stories**: Show components working together - **Real-World Scenarios**: Create stories that demonstrate actual usage patterns ```typescript const meta: Meta = { component: List, decorators: [ moduleMetadata({ declarations: [List, ListItem], }), ], }; export const WithItems: Story = { render: args => ({ props: args, template: ` Item 1 Item 2 Item 3 `, }), }; ``` ## 6. Testing Integration (Storybook 9.x) ### Vitest Addon Integration - **Modern Testing**: Use `@storybook/addon-vitest` for component testing - **Story-Based Tests**: Transform stories into tests automatically - **Browser Mode**: Leverage Vitest's browser mode for realistic testing ```bash # Install and configure Vitest addon npx storybook@latest add @storybook/addon-vitest ``` ### Interaction Testing - **Play Functions**: Use play functions for interaction testing - **User Events**: Simulate real user interactions - **Assertions**: Include meaningful assertions in play functions ```typescript import { userEvent, within, expect } from '@storybook/test'; export const InteractiveTest: Story = { args: { label: 'Click me', }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); const button = canvas.getByRole('button'); await userEvent.click(button); await expect(button).toHaveClass('clicked'); }, }; ``` ### Accessibility Testing - **A11y Addon**: Include `@storybook/addon-a11y` for accessibility checks - **ARIA Labels**: Ensure proper ARIA labeling in stories - **Keyboard Navigation**: Test keyboard accessibility ```typescript const meta: Meta = { component: Button, parameters: { a11y: { config: { rules: [ { id: 'color-contrast', enabled: true, }, ], }, }, }, }; ``` ## 7. Documentation & Docs Integration ### Compodoc Integration - **API Documentation**: Integrate Compodoc for automatic API docs generation - **Angular.json Configuration**: Configure builders for Compodoc integration ```json // angular.json { "projects": { "your-project": { "architect": { "storybook": { "builder": "@storybook/angular:start-storybook", "options": { "compodoc": true, "compodocArgs": ["-e", "json", "-d", "."] } } } } } } ``` ```typescript // .storybook/preview.ts import { setCompodocJson } from '@storybook/addon-docs/angular'; import docJson from '../documentation.json'; setCompodocJson(docJson); ``` ### Story Documentation - **JSDoc Comments**: Use JSDoc comments for automatic documentation - **Description Parameters**: Override descriptions when needed - **Code Examples**: Include relevant code examples ```typescript /** * Primary button component for user actions. * Supports various sizes and states. */ const meta: Meta = { component: Button, parameters: { docs: { description: { component: 'The primary button component with full accessibility support.', }, }, }, }; /** * The primary button state - used for main actions */ export const Primary: Story = { parameters: { docs: { description: { story: 'Use this variant for primary actions like "Save" or "Submit".', }, }, }, }; ``` ## 8. Performance & Optimization ### Lazy Loading - **Code Splitting**: Leverage Angular's lazy loading for large component libraries - **Story Optimization**: Keep stories focused and lightweight - **Asset Management**: Optimize images and other assets ### Bundle Optimization - **Tree Shaking**: Ensure proper tree shaking of unused code - **Minimal Dependencies**: Import only necessary dependencies - **Build Configuration**: Optimize build configuration for production ## 9. Theming & Styling ### Angular Material Integration - **Theme Providers**: Use decorators to provide Angular Material themes - **Component Wrapper**: Wrap stories with theme providers when needed ```typescript import { componentWrapperDecorator } from '@storybook/angular'; const meta: Meta = { component: MyComponent, decorators: [componentWrapperDecorator(story => `${story}`)], }; ``` ### CSS Custom Properties - **Design Tokens**: Use CSS custom properties for consistent theming - **Theme Switching**: Implement theme switching in stories - **Responsive Design**: Test components across different viewports ## 10. File Organization & Naming ### File Structure - **Co-location**: Keep stories close to their components - **Consistent Naming**: Use consistent naming patterns - **Logical Grouping**: Group related stories together ``` src/ components/ button/ button.component.ts button.component.html button.component.scss button.component.stories.ts button.component.spec.ts ``` ### Naming Conventions - **Story Files**: Use `.stories.ts` extension - **Export Names**: Use PascalCase for story exports - **File Names**: Use kebab-case for file names ## 11. CI/CD Integration ### Build Configuration - **Static Builds**: Configure static build for deployment - **Environment Variables**: Handle environment-specific configuration - **Testing Pipeline**: Integrate story testing in CI/CD ```bash # Build Storybook for production ng run your-project:build-storybook # Run tests with Vitest addon npm run test-storybook ``` ### Deployment - **Static Hosting**: Deploy to static hosting services - **Version Management**: Tag releases with version numbers - **Documentation Updates**: Keep documentation in sync with code ## 12. Migration & Maintenance ### Upgrading Storybook - **Regular Updates**: Keep Storybook updated to latest versions - **Migration Guides**: Follow official migration guides - **Breaking Changes**: Test thoroughly after major updates ### Legacy Code Migration - **Gradual Migration**: Migrate stories incrementally - **CSF 2 to CSF 3**: Upgrade older story formats - **Module to Standalone**: Migrate to standalone components when possible ## 13. Common Patterns & Examples ### Form Components ```typescript export const FormExample: Story = { render: args => ({ props: args, template: ` `, }), }; ``` ### Data Loading States ```typescript export const Loading: Story = { args: { loading: true, data: null, }, }; export const WithData: Story = { args: { loading: false, data: mockData, }, }; export const Error: Story = { args: { loading: false, error: 'Failed to load data', }, }; ``` ### Responsive Components ```typescript export const Mobile: Story = { parameters: { viewport: { defaultViewport: 'mobile1', }, }, }; export const Desktop: Story = { parameters: { viewport: { defaultViewport: 'desktop', }, }, }; ``` ## 14. Quality Guidelines ### Code Quality - **TypeScript Strict Mode**: Use strict TypeScript configuration - **ESLint Rules**: Follow Storybook-specific ESLint rules - **Consistent Formatting**: Use Prettier for code formatting ### Testing Standards - **Coverage Goals**: Aim for high story coverage of component states - **Interaction Tests**: Include interaction tests for complex components - **Accessibility Tests**: Ensure all stories pass accessibility checks ### Documentation Standards - **Complete Coverage**: Document all component props and behaviors - **Real Examples**: Provide realistic usage examples - **Up-to-date**: Keep documentation synchronized with code changes ## 15. Troubleshooting & Common Issues ### Angular-Specific Issues - **Module Dependencies**: Ensure all required modules are imported - **Provider Configuration**: Check provider setup for dependency injection - **Change Detection**: Consider OnPush change detection strategy ### Performance Issues - **Bundle Size**: Monitor and optimize bundle size - **Memory Leaks**: Watch for memory leaks in complex stories - **Build Time**: Optimize build configuration for faster development This comprehensive guide ensures you're following the latest best practices for Storybook 9.x with Angular, leveraging modern features like the Vitest addon, improved testing capabilities, and optimized development workflows.
--- alwaysApply: true description: Avoid 'else'; prefer guard clauses and polymorphism to keep a linear flow --- ## Do not use the `else` keyword Avoid `else` to reduce branching and nesting. This keeps a linear top-to-bottom reading flow and simplifies methods. ### Preferred alternatives - **Guard clauses (early return/exit)**: handle exceptional cases up front and return immediately. - **Polymorphism**: for complex conditional logic based on type/state, use Strategy/State instead of chained conditionals. ### Example (guard clause) ❌ Bad: ```ts function processPayment(payment: Payment): boolean { if (payment.isVerified()) { console.log("Processing payment..."); return true; } else { console.log("Payment not verified."); return false; } } ``` ✅ Good: ```ts function processPayment(payment: Payment): boolean { // Guard clause if (!payment.isVerified()) { console.log("Payment not verified."); return false; } // Happy path console.log("Processing payment..."); return true; } ```
# Code Style and Conventions Standards for TypeScript This document outlines coding style and conventions standards for TypeScript development. Adhering to these standards promotes code consistency, readability, maintainability, and collaboration within development teams. These guidelines are tailored for the latest version of TypeScript and aim to leverage modern best practices. ## 1. Formatting Consistent formatting is crucial for readability. We adopt the following standards for TypeScript code formatting: ### 1.1. Whitespace and Indentation * **Standard:** Use 2 spaces for indentation. Avoid tabs. * **Why:** Consistent indentation enhances readability and reduces visual clutter. * **Do This:** """typescript function calculateArea(width: number, height: number): number { const area = width * height; return area; } """ * **Don't Do This:** """typescript function calculateArea(width: number, height: number): number { const area = width * height; return area; } """ * **Standard:** Use blank lines to separate logical sections of code within functions and classes. * **Why:** Separating logical blocks improves code comprehension. * **Do This:** """typescript function processData(data: any[]): void { // Validate data if (!data || data.length === 0) { throw new Error("Data is invalid."); } // Transform data const transformedData = data.map(item => ({ ...item, processed: true, })); // Save data saveToDatabase(transformedData); } """ ### 1.2. Line Length * **Standard:** Limit lines to a maximum of 120 characters. * **Why:** Enforces readability on various screen sizes and IDE configurations. * **How:** Configure your editor or IDE to display a line length guide at 120 characters. Break long lines at logical points, such as after commas, operators, or before opening parentheses. * **Do This:** """typescript const veryLongVariableName = calculateSomethingComplicated( param1, param2, param3 ); """ * **Don't Do This:** """typescript const veryLongVariableName = calculateSomethingComplicated(param1, param2, param3); """ ### 1.3. Braces and Parentheses * **Standard:** Use braces for all control flow statements, even single-line statements. * **Why:** Improves code clarity and reduces potential errors when modifying code. * **Do This:** """typescript if (isValid) { console.log("Valid"); } else { console.log("Invalid"); } """ * **Don't Do This:** """typescript if (isValid) console.log("Valid"); else console.log("Invalid"); """ * **Standard:** Use parentheses to clarify operator precedence, where needed. * **Why:** Reduces ambiguity, especially in complex expressions. * **Example:** """typescript const result = (a + b) * c; """ ### 1.4. Semicolons * **Standard:** Always use semicolons to terminate statements. * **Why:** Prevents unexpected behavior due to JavaScript's automatic semicolon insertion (ASI). * **Do This:** """typescript const name = "John"; console.log(name); """ * **Don't Do This:** """typescript const name = "John" console.log(name) """ ## 2. Naming Conventions Consistent naming conventions are essential for code clarity and maintainability. ### 2.1. Variables and Constants * **Standard:** Use camelCase for variable and constant names. * **Why:** Widely adopted convention for JavaScript and TypeScript. * **Do This:** """typescript const userName = "Alice"; let itemCount = 0; """ * **Standard:** Use UPPER_SNAKE_CASE for constant values (i.e. values that may be inlined for performance or are known at compile time). * **Why:** Clearly distinguishes constants from variables. * **Do This:** """typescript const MAX_RETRIES = 3; const API_ENDPOINT = "https://example.com/api"; """ ### 2.2. Functions and Methods * **Standard:** Use camelCase for function and method names. * **Why:** Follows common JavaScript/TypeScript conventions. * **Do This:** """typescript function calculateTotal(price: number, quantity: number): number { return price * quantity; } class ShoppingCart { addItem(item: string): void { console.log("Adding ${item} to the cart."); } } """ ### 2.3. Classes and Interfaces * **Standard:** Use PascalCase for class and interface names. * **Why:** Clearly identifies classes and interfaces. * **Do This:** """typescript interface User { id: number; name: string; } class Product { constructor(public name: string, public price: number) {} } """ ### 2.4. Type Parameters * **Standard:** Use single uppercase letters, typically "T", "U", "V", etc., for generic type parameters. * **Why:** Follows established TypeScript conventions. * **Do This:** """typescript function identity<T>(arg: T): T { return arg; } """ ### 2.5. Boolean Variables * **Standard:** Prefix boolean variables with "is", "has", or "should" to indicate a boolean value. * **Why:** Improves readability by clearly indicating the purpose of the variable. * **Do This:** """typescript let isValid: boolean = true; let hasPermission: boolean = false; let shouldUpdate: boolean = true; """ ## 3. Stylistic Consistency Consistency in style is critical for code maintainability. ### 3.1. Type Annotations and Inference * **Standard:** Use explicit type annotations where type inference is not obvious, especially for function parameters and return types. * **Why:** Improves code clarity and helps catch type-related errors early. * **Do This:** """typescript function greet(name: string): string { return "Hello, ${name}!"; } const add: (x: number, y: number) => number = (x, y) => x + y; """ * **Don't Do This:** """typescript function greet(name) { // Implicit 'any' type return "Hello, ${name}!"; } """ * **Standard:** Leverage type inference for local variables when the type is immediately apparent. * **Why:** Reduces verbosity and keeps code concise. * **Do This:** """typescript const message = "Hello, world!"; // Type inferred as string const count = 10; // Type inferred as number """ * **Standard:** When initializing variables with "null" or "undefined", explicitly define the type. * **Why:** Helps avoid unexpected type-related issues later. * **Do This:** """typescript let user: User | null = null; let data: string[] | undefined = undefined; """ ### 3.2. String Usage * **Standard:** Prefer template literals for string concatenation and multi-line strings. * **Why:** More readable and easier to maintain compared to traditional string concatenation. * **Do This:** """typescript const name = "Alice"; const message = "Hello, ${name}!"; const multiLine = "This is a multi-line string."; """ * **Don't Do This:** """typescript const name = "Alice"; const message = "Hello, " + name + "!"; const multiLine = "This is a\n" + "multi-line string."; """ ### 3.3. Object Literals * **Standard:** Use shorthand notation for object properties when the property name matches the variable name. * **Why:** Improves code conciseness and readability. * **Do This:** """typescript const name = "Alice"; const age = 30; const user = { name, age }; // Shorthand notation """ * **Don't Do This:** """typescript const name = "Alice"; const age = 30; const user = { name: name, age: age }; """ * **Standard:** Use object spread syntax for creating copies of objects or merging objects. * **Why:** More concise and readable than older methods like "Object.assign()". * **Do This:** """typescript const original = { a: 1, b: 2 }; const copy = { ...original, c: 3 }; // Creates a new object with a, b, and c """ ### 3.4. Arrow Functions * **Standard:** Use arrow functions for concise function expressions, especially for callbacks and inline functions. * **Why:** More compact syntax and lexically binds "this". * **Do This:** """typescript const numbers = [1, 2, 3]; const squared = numbers.map(x => x * x); // Concise arrow function """ * **Don't Do This:** """typescript const numbers = [1, 2, 3]; const squared = numbers.map(function(x) { return x * x; }); """ * **Standard:** Omit parentheses for single-parameter arrow functions. * **Why:** Makes the code even more concise. * **Do This:** """typescript const increment = x => x + 1; """ * **Don't Do This:** """typescript const increment = (x) => x + 1; """ ### 3.5. Modern TypeScript Features * **Standard:** Leverage features like optional chaining ("?.") and nullish coalescing ("??") for safer and more concise code. Optional properties on interfaces may be relevant if these are in use. * **Why:** Reduces boilerplate and improves null/undefined handling. * **Do This:** """typescript interface User { profile?: { address?: { city?: string; } } } const user: User = {}; const city = user?.profile?.address?.city ?? "Unknown"; // Nullish coalescing console.log(city); interface Config { timeout?: number; } const defaultConfig: Config = { timeout: 5000, }; function initialize(config?: Config) { const timeout = config?.timeout ?? defaultConfig.timeout; console.log("Timeout: ${timeout}"); } initialize(); // Timeout: 5000 initialize({ timeout: 10000 }); // Timeout: 10000 """ * **Standard:** Utilize discriminated unions and exhaustive checks for increased type safety and maintainability. * **Why:** Improves type correctness and makes it easier to handle different states or object types. * **Do This:** """typescript interface Success { type: "success"; result: any; } interface Error { type: "error"; message: string; } type Result = Success | Error; function handleResult(result: Result) { switch (result.type) { case "success": console.log("Success:", result.result); break; case "error": console.error("Error:", result.message); break; default: // Exhaustive check: TypeScript will flag this if a new type is added to Result const _exhaustiveCheck: never = result; return _exhaustiveCheck; } } const successResult: Success = { type: "success", result: { data: "example" } }; const errorResult: Error = { type: "error", message: "Something went wrong" }; handleResult(successResult); handleResult(errorResult); """ ### 3.6. Asynchronous Code * **Standard:** Always use "async/await" syntax for asynchronous operations. * **Why:** Improves readability and simplifies error handling compared to traditional promise chains. * **Do This:** """typescript async function fetchData(): Promise<any> { try { const response = await fetch("https://example.com/api/data"); const data = await response.json(); return data; } catch (error) { console.error("Error fetching data:", error); throw error; } } """ * **Don't Do This:** """typescript function fetchData(): Promise<any> { return fetch("https://example.com/api/data") .then(response => response.json()) .then(data => data) .catch(error => { console.error("Error fetching data:", error); throw error; }); } """ * **Standard:** Use "Promise.all" for concurrent asynchronous operations that don't depend on each other. * **Why:** Improves performance by executing asynchronous tasks in parallel. * **Do This:** """typescript async function processData(): Promise<void> { const [result1, result2] = await Promise.all([ fetchData1(), fetchData2(), ]); console.log("Result 1:", result1); console.log("Result 2:", result2); } """ ### 3.7 Error Handling * **Standard:** Implement robust error handling using "try...catch" blocks, especially in asynchronous functions. * **Why:** Prevents unhandled exceptions and allows for graceful recovery. * **Do This:** """typescript async function doSomething() { try { const result = await someAsyncOperation(); console.log("Result:", result); } catch (error) { console.error("An error occurred:", error); // Implement specific error handling/logging } } """ * **Standard:** Create custom error classes to provide more context and specify error handling logic. * **Why:** Extends the built-in Error to communicate more specific information about the error to the outside world. * **Do This:** """typescript class CustomError extends Error { constructor(message: string, public errorCode: number) { super(message); this.name = "CustomError"; Object.setPrototypeOf(this, CustomError.prototype); } } async function performOperation() { try { // some operation throw new CustomError("Operation failed", 500); } catch (error) { if (error instanceof CustomError) { console.error("Custom Error ${error.errorCode}: ${error.message}"); } else { console.error("An unexpected error occurred:", error); } } } """ ### 3.8 Immutability * **Standard:** Strive for immutability whenever practical, using "const" for variables that should not be reassigned and avoiding direct modification of objects and arrays. * **Why:** Makes code more predictable and easier to reason about, reducing the risk of bugs. * **Do This:** """typescript const originalArray = [1, 2, 3]; const newArray = [...originalArray, 4]; // Creates a new array const originalObject = { a: 1, b: 2 }; const newObject = { ...originalObject, c: 3 }; // Creates a new object """ * **Don't Do This:** """typescript const originalArray = [1, 2, 3]; originalArray.push(4); // Modifies the original array const originalObject = { a: 1, b: 2 }; originalObject.c = 3; // Modifies the original object """ ### 3.9 Comments * **Standard:** Add comments to explain complex or non-obvious logic, but prioritize writing self-documenting code. * **Why:** Comments should supplement, not replace, clear code. * **Guidelines:** * Use JSDoc-style comments for documenting functions, classes, and interfaces. * Explain the *why*, not the *what*. The code should explain what it does. * Keep comments concise and up-to-date. * Remove outdated or redundant comments. * **Example:** """typescript /** * Calculates the area of a rectangle. * @param width The width of the rectangle. * @param height The height of the rectangle. * @returns The area of the rectangle. */ function calculateArea(width: number, height: number): number { return width * height; } """ ## 4. Technology Specific Details (Distinguishing Good from Great) * **Standard:** Take advantage of TypeScript's advanced type features to create robust and maintainable code structures. * **Guidelines:** * **Utility Types:** Employ TypeScript's utility types ("Partial", "Readonly", "Pick", "Omit", "Record", etc.) to manipulate types and generate new types efficiently. """typescript interface User { id: number; name: string; email: string; age: number; } // Make all properties optional type PartialUser = Partial<User>; // Make specified properties required type RequiredIdAndName = Required<Pick<User, 'id' | 'name'>>; // Type with only certain properties type UserInfo = Pick<User, 'name' | 'email'>; // Type without certain properties type UserWithoutId = Omit<User, 'id'>; """ * **Mapped Types:** Utilize mapped types to transform the properties of an existing type, providing a dynamic way to define new types based on existing ones. """typescript interface Product { id: string; name: string; price: number; } // Create a read-only version of Product type ReadonlyProduct = Readonly<Product>; // Create a type where all properties of Product are nullable type NullableProduct = { [K in keyof Product]: Product[K] | null; }; """ * **Conditional Types:** Conditional types allow to define types based on conditions, adding yet another powerful layer of abstraction to type definitions. They help to ensure type safety throughout an application. """typescript type NonNullableProperty<T, K extends keyof T> = T[K] extends null | undefined ? never : K; type RequiredProperties<T> = Pick<T, NonNullableProperty<T, keyof T>>; interface Configuration { host?: string; port?: number; // Port can be potentially undefined or null timeout?: number; } // Extracts properties that are guaranteed to be assigned during runtime. type RuntimeProperties = RequiredProperties<Configuration>; // Result equivalent to {timeout: number;} """ * **Decorators:** Use decorators to add metadata or modify the behavior of classes, methods, properties, or parameters. * **Why:** Provide a declarative and reusable way to add functionality, such as logging, validation, or dependency injection. * **Example:** """typescript function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log("Calling method ${propertyKey} with arguments: ${JSON.stringify(args)}"); const result = originalMethod.apply(this, args); console.log("Method ${propertyKey} returned: ${result}"); return result; }; return descriptor; } class Calculator { @logMethod add(a: number, b: number): number { return a + b; } } const calculator = new Calculator(); calculator.add(2, 3); // Output: // Calling method add with arguments: [2,3] // Method add returned: 5 """ ## 5. Tooling * **Standard:** Use Prettier for automatic code formatting and ESLint with recommended TypeScript rules for linting. * **Why:** Automates formatting and enforces code quality, reducing manual effort and improving consistency. * **Configuration:** Configure Prettier and ESLint to work seamlessly with your IDE and CI/CD pipeline. * **Example ".eslintrc.js" configuration:** """javascript module.exports = { parser: "@typescript-eslint/parser", parserOptions: { ecmaVersion: 2020, sourceType: "module", project: './tsconfig.json', }, plugins: ["@typescript-eslint"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", ], rules: { // Add or override rules here }, }; """ By adhering to these coding standards, TypeScript projects will benefit from improved code quality, readability, and maintainability, fostering a collaborative and productive development environment.