UNPKG

@writely/preview

Version:

Lightning-fast development server with live preview for Writely blogs. Hot reload, file watching, and instant feedback for the best development experience.

328 lines (252 loc) • 9.83 kB
# @writely/preview Development server and preview environment for the Writely blog platform. Provides a Next.js-based development server with hot reload, file watching, and static site generation capabilities for local blog development and testing. ## Features - **Development Server**: Next.js-based preview server with hot reload and file watching - **Hot Reload**: Instant updates when MDX files are modified with live preview - **File Watching**: Automatic detection and processing of new, modified, and deleted files - **Static Site Generation**: Generate production-ready static sites with optimization - **Theme Integration**: Seamless integration with all Writely themes and layouts - **MDX Processing**: Advanced MDX processing with syntax highlighting and math rendering - **SEO Preview**: Built-in SEO preview tools and meta tag management - **Asset Handling**: Automatic handling of static assets and public files - **Error Recovery**: Robust error handling with automatic recovery and helpful messages - **Performance Monitoring**: Built-in performance monitoring and optimization tools - **Cross-Platform**: Works on Windows, macOS, and Linux with consistent behavior - **Configuration Validation**: Automatic validation of blog configuration and content ## Installation ```bash # Install the preview package npm install @writely/preview # Install with peer dependencies npm install @writely/preview @writely/core @writely/mdx next ``` ## API ### Preview Server ```typescript import { startPreview, PreviewServer, PreviewOptions } from "@writely/preview"; // Start development server with default options const server = await startPreview({ config: blogConfig, port: 3000, host: "localhost", open: true, }); // Use PreviewServer class for more control const previewServer = new PreviewServer({ config: blogConfig, port: 3000, host: "localhost", open: true, }); await previewServer.start(); // Access server properties const files = previewServer.files; // Stop the server await previewServer.stop(); ``` ### Static Site Generation ```typescript import { StaticSiteGenerator, StaticSiteOptions } from "@writely/preview"; // Generate static site const generator = new StaticSiteGenerator(blogConfig, mdxFiles, "./dist"); await generator.generate(); // Static site generation includes: // - HTML pages for all MDX files // - Sitemap.xml generation // - RSS feed generation // - Static asset copying // - Build manifest creation ``` ### Configuration Options ```typescript interface PreviewOptions { /** Blog configuration object */ config: BlogConfig; /** Port to run the server on (default: 3000) */ port?: number; /** Host to bind the server to (default: localhost) */ host?: string; /** Whether to open browser automatically (default: true) */ open?: boolean; } interface StaticSiteOptions { /** Output directory for generated files */ outputDir: string; /** Base URL for the site (default: from config) */ baseUrl?: string; /** Whether to generate sitemap.xml (default: true) */ generateSitemap?: boolean; /** Whether to generate RSS feed (default: true) */ generateRSS?: boolean; } ``` ### File Watching and Hot Reload ```typescript // The preview server automatically watches for file changes: // - MDX files in content directory // - Configuration files (blog.json) // - Static assets in public directory // - Theme files and components // When files change: // 1. File is detected by the watcher // 2. MDX content is reprocessed with syntax highlighting // 3. Server rebuilds affected pages // 4. Browser is automatically refreshed // 5. Live reload updates the preview ``` ### Error Handling ```typescript // The preview server provides comprehensive error handling: // File not found errors if (errorMessage.includes("ENOENT")) { console.log("šŸ’” Check if the directory exists"); } // Port already in use errors if (errorMessage.includes("EADDRINUSE")) { console.log("šŸ’” Try using a different port with --port option"); } // Permission errors if (errorMessage.includes("permission")) { console.log( "šŸ’” Try running with elevated permissions or check file permissions", ); } ``` ## Configuration ### Blog Configuration The preview server uses the same blog configuration as other Writely packages: ```json { "title": "My Blog", "description": "A beautiful blog built with Writely", "author": "Your Name", "url": "https://myblog.com", "language": "en", "theme": "nova", "seo": { "metatags": { "description": "My blog description", "keywords": "blog, writely, mdx" } }, "content": { "postsPerPage": 10, "defaultLayout": "post" } } ``` ### Development Configuration ```typescript // Default development settings const defaultOptions = { port: 3000, host: "localhost", open: true, watchPatterns: ["content/**/*.mdx", "public/**/*", "blog.json", "theme/**/*"], }; ``` ### File Structure Detection The preview server automatically detects your blog structure: ```typescript // Detected structure interface BlogStructure { mdxFiles: string[]; // All MDX files found hasPublicFolder: boolean; // Whether public folder exists hasFavicon: boolean; // Whether favicon exists } ``` ## Development ### Prerequisites - Node.js 18.0.0 or higher - TypeScript 5.3.0 or higher - Next.js 15.0.0 or higher ### Setup ```bash # Clone the repository git clone https://github.com/WritelyBlog/writely.git cd writely/packages/@writely/preview # Install dependencies pnpm install # Build the package pnpm build # Run in development mode pnpm dev ``` ### Development Workflow 1. **Install Dependencies**: `pnpm install` 2. **Build Package**: `pnpm build` 3. **Run Tests**: `pnpm test` 4. **Lint Code**: `pnpm lint` 5. **Watch Mode**: `pnpm dev` ## Scripts - `pnpm build` - Build the preview package with TypeScript compilation - `pnpm dev` - Watch mode for development with hot reload - `pnpm lint` - Run ESLint with TypeScript support - `pnpm clean` - Clean build artifacts and temporary files - `pnpm test` - Run unit and integration tests - `pnpm type-check` - Run TypeScript type checking - `pnpm format` - Format code with Prettier - `pnpm validate` - Validate package configuration and dependencies ## Architecture The preview package is structured for performance, reliability, and extensibility: ``` src/ ā”œā”€ā”€ index.ts # Main exports and server implementation ā”œā”€ā”€ app/ # Next.js app directory │ ā”œā”€ā”€ layout.tsx # Root layout component │ ā”œā”€ā”€ page.tsx # Home page component │ └── [...slug]/ # Dynamic route handling │ └── page.tsx # MDX page rendering └── package.json # Package configuration ``` ### Core Components **Preview Server**: Next.js-based development server with Express middleware and Socket.IO for live reload. **File Watcher**: Chokidar-based file watching with intelligent pattern matching and debouncing. **MDX Processor**: Integration with @writely/mdx for advanced content processing and syntax highlighting. **Theme Renderer**: Seamless integration with @writely/core themes for consistent rendering. **Static Generator**: Complete static site generation with sitemap, RSS, and asset optimization. **Error Handler**: Comprehensive error handling with helpful suggestions and automatic recovery. **Performance Monitor**: Built-in performance monitoring and optimization tools. **Asset Manager**: Automatic handling of static assets, public files, and theme resources. **Configuration Validator**: Automatic validation of blog configuration and content structure. **Cross-Platform Support**: Consistent behavior across Windows, macOS, and Linux platforms. ### Server Architecture ``` PreviewServer ā”œā”€ā”€ Next.js App # Main application server ā”œā”€ā”€ Express Middleware # Custom middleware and routing ā”œā”€ā”€ Socket.IO Server # Live reload and real-time updates ā”œā”€ā”€ File Watcher # Chokidar-based file monitoring ā”œā”€ā”€ MDX Processor # Content processing and validation ā”œā”€ā”€ Theme Renderer # Theme integration and rendering └── Error Handler # Error handling and recovery ``` ### Static Generation Process ``` StaticSiteGenerator ā”œā”€ā”€ Page Generation # HTML page generation from MDX ā”œā”€ā”€ Asset Copying # Static asset copying and optimization ā”œā”€ā”€ Sitemap Generation # XML sitemap generation ā”œā”€ā”€ RSS Feed Generation # RSS feed generation ā”œā”€ā”€ Build Manifest # Build manifest and metadata └── Output Optimization # Final optimization and validation ``` ## Contributing 1. **Fork Repository**: Create a fork of the main repository 2. **Create Feature Branch**: `git checkout -b feature/new-preview-feature` 3. **Make Changes**: Implement new functionality with proper TypeScript types 4. **Add Tests**: Include unit tests for new server features and utilities 5. **Update Documentation**: Update README and API documentation 6. **Run Validation**: Ensure all tests pass and code is properly formatted 7. **Submit Pull Request**: Create detailed pull request with description ### Development Guidelines - Follow TypeScript best practices with strict type checking - Implement comprehensive error handling with helpful error messages - Add unit tests for all new server features and utilities - Maintain backward compatibility for existing APIs - Use consistent naming conventions for functions and types - Follow the established code style and architecture patterns - Ensure all server features have proper error handling and performance optimization - Test cross-platform compatibility for all new features ## License MIT License - see [LICENSE](./LICENSE) for details.