mpan.dev Technical Blog

website·Indexed 29 days ago

https://mpan.dev

A collection of technical guides and articles covering frontend engineering, including frontend testing models (Pyramid and Trophy), Prettier architecture, Git Flow best practices, Astro framework, and the evolution of frontend development.

Tokens
8.8K
Snippets
33
Records
60
Agent score
50%

What's inside mpan.dev

  1. Overview of Frontend Evolution Phases

    Frontend development has evolved through five primary stages to improve User Experience (UX) and Developer Experience (DX):

    1. Static Era (Web 1.0, 1990s): Server-side string concatenation (JSP, PHP, ASP) producing static HTML. High latency due to full page reloads.
    2. Dynamic Interaction Era (2000s-2010): Introduction of JavaScript and AJAX for partial page updates. jQuery standardized DOM manipulation across browsers.
    3. Engineering Enlightenment (2010-2013): Introduction of MVC/MVVM patterns (e.g., AngularJS) and two-way data binding to decouple data from views.
    4. Component-Based Era (2013-Present): Shift to Single Page Applications (SPA) using Virtual DOM and declarative UI (React, Vue, Angular). Focus on reusable components and unidirectional data flow.
    5. Meta-Framework & SSR Era (2016-Present): Use of frameworks like Next.js and Nuxt.js to solve SEO and initial load performance via Server-Side Rendering (SSR) and Static Site Generation (SSG).
  2. Overview of the Git Flow branching model

    Git Flow is a Git-based branching model designed for projects with explicit release cycles (e.g., versioned releases like V1.0, V2.0) or those needing to maintain old versions while developing new ones. It uses a strict structure of long-lived and short-lived branches to manage the software release lifecycle.
  3. Overview of Astro Framework

    Astro is a web framework optimized for content-driven websites such as blogs, documentation, marketing pages, and portfolios. Its primary goal is to maximize performance by rendering pages to static HTML by default and minimizing the JavaScript sent to the browser. It is particularly effective for sites where the majority of the content is text and images with limited interactivity.
  4. Best practices for optimizing Astro performance

    To maximize the benefits of Astro's architecture, follow these implementation principles:

    1. Prioritize static components: Write components as static by default. Only add client directives when the component specifically requires browser events, state, or API access.
    2. Limit client:load usage: Minimize the number of components activated immediately on the first screen to avoid degrading performance.
    3. Implement schemas for content fields: Use schemas to validate fields such as title, description, tags, publish date, and draft status during the build phase.
    4. Centralize content structure: Generate features like tags, archives, RSS, search, and OG images from a single source of content data.
    5. Monitor real-world metrics: While Lighthouse scores are useful, prioritize actual first-paint, interaction, and accessibility metrics in real network environments.
  5. Understand Prettier's core design philosophy

    Prettier is an "Opinionated Code Formatter." Its primary goal is to remove style discussions from the development process by delegating formatting decisions to the tool. While it provides a limited set of core options (e.g., printWidth, tabWidth, semi, singleQuote, trailingComma, arrowParens), it intentionally avoids providing configuration for purely aesthetic details (like whether braces should wrap) to ensure consistency and reduce team friction.
  6. Implement Islands Architecture with Astro

    Islands Architecture (implemented by Astro) follows a 'static by default' approach. The server outputs pure HTML, and only specific interactive regions (e.g., carousels, comment sections) are treated as dynamic 'islands'. JS is injected only for these islands, eliminating client-side JS overhead for the rest of the static content. This is highly effective for content-heavy sites like blogs and documentation.
  7. Implement selective hydration using Astro Islands Architecture

    Astro uses 'Islands Architecture' to treat interactive components as isolated islands within a sea of static HTML. You control when a component's JavaScript is loaded and executed using client:* directives. This prevents the entire page from being hydrated if only a few elements need interactivity.
    <!-- Load and hydrate immediately on page load -->
    <InteractiveComponent client:load />
    
    <!-- Hydrate when the browser is idle -->
    <InteractiveComponent client:idle />
    
    <!-- Hydrate only when the component becomes visible in the viewport -->
    <InteractiveComponent client:visible />
    
    <!-- Hydrate only when a specific media query is matched -->
    <InteractiveComponent client:media="(max-width: 768px)" />
    
    <!-- Skip SSR entirely; render only on the client -->
    <InteractiveComponent client:only="react" />
  8. Compare Modern Frontend Frameworks: React, Vue, and Angular

    While all three modern frameworks utilize component-based architecture and Virtual DOM, they differ in philosophy:

    • React: A UI library focusing strictly on the view layer (UI = f(State)). It is highly flexible, relying on a vast ecosystem for routing and state management.
    • Vue.js: A progressive framework. Its primary advantage is the Single File Component (SFC, .vue files) which co-locates template, script, and style.
    • Angular (2+): A comprehensive platform for enterprise-scale apps. Built with TypeScript, it includes built-in dependency injection, routing, forms, and HTTP clients out-of-the-box.
  9. Automatically sort Tailwind CSS classes

    Use prettier-plugin-tailwindcss to automatically order Tailwind CSS classes according to official recommendations. The plugin must be added to the plugins array in the Prettier configuration. If other formatting plugins are used, prettier-plugin-tailwindcss should be listed last.
    npm install prettier-plugin-tailwindcss -D
    // prettier.config.js
    export default {
      plugins: ['prettier-plugin-tailwindcss'],
    }
  10. Enforce Prettier formatting with Husky and lint-staged

    To ensure all code is formatted before commit regardless of editor settings, use Husky and lint-staged to run Prettier on staged files.
    npm install husky lint-staged -D
    {
      "lint-staged": {
        "*.{js,ts,jsx,tsx}": ["prettier --write"]
      }
    }
  11. Implement Runtime API Schema Validation with Zod

    To prevent application crashes caused by unexpected API response changes (even if TypeScript types are correct at compile time), use zod for strict runtime validation. By defining a schema and using safeParse, the application can detect and handle contract breaches immediately when data is received from the network.
    import { z } from 'zod'
    
    // Define the runtime contract schema
    export const UserResponseSchema = z.object({
      id: z.string(),
      username: z.string(),
      email: z.string().email(),
      avatarUrl: z.string().url().optional(),
      status: z.enum(['active', 'suspended', 'pending']),
    })
    
    export type UserResponse = z.infer<typeof UserResponseSchema>
    
    // Request wrapper with contract validation
    export async function fetchUserProfile(userId: string): Promise<UserResponse> {
      const response = await fetch(`/api/users/${userId}`)
      if (!response.ok) throw new Error(`HTTP Error ${response.status}`)
    
      const rawData = await response.json()
      
      // Strict Parse: triggers error if backend returns unexpected fields or types
      const parseResult = UserResponseSchema.safeParse(rawData)
      if (!parseResult.success) {
        console.error('API Contract Breach:', parseResult.error.format())
        throw new Error('API response violates frontend contract specifications')
      }
      return parseResult.data
    }
    
  12. Add XML support to Prettier

    Install @prettier/plugin-xml and add it to the plugins array in your configuration to enable formatting for .xml files.
    npm install @prettier/plugin-xml -D