@writely/preview
v0.0.4
Published
Lightning-fast development server with live preview for Writely blogs. Hot reload, file watching, and instant feedback for the best development experience.
Maintainers
Readme
@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
# Install the preview package
npm install @writely/preview
# Install with peer dependencies
npm install @writely/preview @writely/core @writely/mdx nextAPI
Preview Server
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
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 creationConfiguration Options
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
// 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 previewError Handling
// 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:
{
"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
// 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:
// 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
# 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 devDevelopment Workflow
- Install Dependencies:
pnpm install - Build Package:
pnpm build - Run Tests:
pnpm test - Lint Code:
pnpm lint - Watch Mode:
pnpm dev
Scripts
pnpm build- Build the preview package with TypeScript compilationpnpm dev- Watch mode for development with hot reloadpnpm lint- Run ESLint with TypeScript supportpnpm clean- Clean build artifacts and temporary filespnpm test- Run unit and integration testspnpm type-check- Run TypeScript type checkingpnpm format- Format code with Prettierpnpm 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 configurationCore 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 recoveryStatic 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 validationContributing
- Fork Repository: Create a fork of the main repository
- Create Feature Branch:
git checkout -b feature/new-preview-feature - Make Changes: Implement new functionality with proper TypeScript types
- Add Tests: Include unit tests for new server features and utilities
- Update Documentation: Update README and API documentation
- Run Validation: Ensure all tests pass and code is properly formatted
- 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 for details.
