CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-snowpack

A lightning-fast frontend build tool designed to leverage JavaScript's native ESM system for unbundled development with instant browser updates.

82

1.22x
Overview
Eval results
Files

development-server.mddocs/

Development Server

The Snowpack development server provides instant file building, hot module replacement, and unbundled development for modern web applications. It serves files individually as ES modules directly to the browser, eliminating bundling overhead during development.

Capabilities

Server Management

Start and manage the development server instance with configuration options.

/**
 * Start the Snowpack development server
 * @param commandOptions - Configuration and lockfile options
 * @param options - Optional server configuration
 * @returns Promise resolving to development server instance
 */
function startServer(
  commandOptions: CommandOptions,
  options?: {
    isDev?: boolean;
    isWatch?: boolean;
    preparePackages?: boolean;
  }
): Promise<SnowpackDevServer>;
import { startServer, loadConfiguration } from "snowpack";

// Basic server startup
const config = await loadConfiguration();
const server = await startServer({ config });

// Server startup with lockfile
const lockfile = await loadLockfile(process.cwd());
const server = await startServer({ config, lockfile });

// Server startup with options
const server = await startServer({ config }, {
  isDev: true,
  isWatch: true,
  preparePackages: true
});

console.log(`Development server running on port ${server.port}`);

File Loading and Processing

Load and process files through the development server pipeline.

/**
 * Load a URL through the development server
 * @param reqUrl - Request URL to load
 * @param options - Optional load options
 * @returns Promise resolving to load result or undefined
 */
loadUrl(reqUrl: string, options?: LoadUrlOptions): Promise<LoadResult<Buffer | string> | undefined>;

/**
 * Load a URL with specific encoding
 * @param reqUrl - Request URL to load
 * @param options - Load options with encoding specification
 * @returns Promise resolving to load result with specified encoding
 */
loadUrl(reqUrl: string, options: LoadUrlOptions & {encoding: BufferEncoding}): Promise<LoadResult<string> | undefined>;

/**
 * Load a URL as buffer
 * @param reqUrl - Request URL to load
 * @param options - Load options with null encoding
 * @returns Promise resolving to load result as buffer
 */
loadUrl(reqUrl: string, options: LoadUrlOptions & {encoding: null}): Promise<LoadResult<Buffer> | undefined>;
// Load file as string
const result = await server.loadUrl('/src/app.js', { encoding: 'utf8' });
if (result) {
  console.log('File contents:', result.contents);
  console.log('Imports found:', result.imports);
}

// Load file for SSR
const ssrResult = await server.loadUrl('/src/component.js', { isSSR: true });

// Load file as buffer
const bufferResult = await server.loadUrl('/assets/image.png', { encoding: null });

Request Handling

Handle HTTP requests and responses through the development server.

/**
 * Handle incoming HTTP requests
 * @param req - HTTP request object
 * @param res - HTTP response object
 * @param options - Optional handling options
 * @returns Promise resolving when request is handled
 */
handleRequest(req: http.IncomingMessage, res: http.ServerResponse, options?: {handleError?: boolean}): Promise<void>;

/**
 * Send a file response
 * @param req - HTTP request object
 * @param res - HTTP response object
 * @param result - Load result to send
 */
sendResponseFile(req: http.IncomingMessage, res: http.ServerResponse, result: LoadResult): void;

/**
 * Send an error response
 * @param req - HTTP request object
 * @param res - HTTP response object
 * @param status - HTTP status code
 */
sendResponseError(req: http.IncomingMessage, res: http.ServerResponse, status: number): void;
import http from 'http';

// Create custom server using Snowpack handler
const customServer = http.createServer(async (req, res) => {
  try {
    await server.handleRequest(req, res);
  } catch (error) {
    await server.handleRequest(req, res, { handleError: true });
  }
});

// Manual file serving
const result = await server.loadUrl(req.url);
if (result) {
  server.sendResponseFile(req, res, result);
} else {
  server.sendResponseError(req, res, 404);
}

URL Resolution

Resolve file paths to URLs and package specifiers to URLs.

/**
 * Get URL for a file location
 * @param fileLoc - File location path
 * @returns File URL or null if not found
 */
getUrlForFile(fileLoc: string): string | null;

/**
 * Get URL for a package specifier
 * @param packageSpec - Package specifier (e.g., "react")
 * @returns Promise resolving to package URL
 */
getUrlForPackage(packageSpec: string): Promise<string>;
// Get URL for local file
const fileUrl = server.getUrlForFile('/src/components/Button.jsx');
// Result: "/src/components/Button.js"

// Get URL for npm package
const packageUrl = await server.getUrlForPackage('react');
// Result: "/web_modules/react.js"

Server-Side Rendering

Get server runtime for executing modules server-side.

/**
 * Get server runtime for SSR
 * @param options - Optional runtime options
 * @returns Server runtime instance
 */
getServerRuntime(options?: {invalidateOnChange?: boolean}): ServerRuntime;

/**
 * Server runtime for importing and executing modules server-side
 */
interface ServerRuntime {
  /** Import a module server-side */
  importModule<T = any>(url: string): Promise<ServerRuntimeModule<T>>;
  /** Invalidate a cached module */
  invalidateModule(url: string): void;
}

/**
 * Server-side module wrapper
 */
interface ServerRuntimeModule<T extends any> {
  /** Module exports */
  exports: T;
  /** Associated CSS files */
  css: string[];
}
// Get server runtime
const runtime = server.getServerRuntime({ invalidateOnChange: true });

// Import module server-side
const appModule = await runtime.importModule('/src/App.js');
const App = appModule.exports.default;
const cssFiles = appModule.css;

// Render component server-side
const html = renderToString(App());

// Invalidate cached module
runtime.invalidateModule('/src/App.js');

File Watching

Monitor file changes during development.

/**
 * Register callback for file changes
 * @param callback - Function to call when files change
 */
onFileChange(callback: OnFileChangeCallback): void;

/**
 * Manually mark a file as changed
 * @param fileLoc - File location that changed
 */
markChanged(fileLoc: string): void;

/**
 * File change callback type
 */
type OnFileChangeCallback = ({filePath: string}) => any;
// Register file change listener
server.onFileChange(({ filePath }) => {
  console.log(`File changed: ${filePath}`);
  // Perform custom handling
});

// Manually trigger file change
server.markChanged('/src/config.js');

Server Lifecycle

Manage server shutdown and cleanup.

/**
 * Shutdown the development server
 * @returns Promise resolving when server is shut down
 */
shutdown(): Promise<void>;
// Graceful server shutdown
process.on('SIGINT', async () => {
  console.log('Shutting down development server...');
  await server.shutdown();
  process.exit(0);
});

Load Options

/**
 * Options for loading URLs through the development server
 */
interface LoadUrlOptions {
  /** Server-side rendering mode */
  isSSR?: boolean;
  /** Hot module replacement mode */
  isHMR?: boolean;
  /** Module resolution mode */
  isResolve?: boolean;
  /** Allow stale cache */
  allowStale?: boolean;
  /** Response encoding */
  encoding?: undefined | BufferEncoding | null;
  /** Import map for resolution */
  importMap?: ImportMap;
}

Server Configuration

The development server behavior is controlled through the devOptions section of the Snowpack configuration:

/**
 * Development server options
 */
interface DevOptions {
  /** HTTPS configuration */
  secure: boolean | {cert: string | Buffer; key: string | Buffer};
  /** Server hostname */
  hostname: string;
  /** Server port */
  port: number;
  /** URL to open in browser */
  openUrl?: string;
  /** Browser to open */
  open?: string;
  /** Output mode */
  output?: 'stream' | 'dashboard';
  /** Enable hot module replacement */
  hmr?: boolean;
  /** HMR delay in milliseconds */
  hmrDelay: number;
  /** HMR port */
  hmrPort: number | undefined;
  /** Show HMR error overlay */
  hmrErrorOverlay: boolean;
  /** Tailwind config path */
  tailwindConfig?: string;
}
// Example server configuration
const config = createConfiguration({
  devOptions: {
    port: 3000,
    hostname: 'localhost',
    hmr: true,
    hmrDelay: 0,
    open: 'chrome',
    output: 'dashboard'
  }
});

const server = await startServer({ config });

Install with Tessl CLI

npx tessl i tessl/npm-snowpack

docs

build-system.md

cli.md

configuration.md

development-server.md

index.md

plugins.md

utilities.md

tile.json