A comprehensive web component compiler that transforms TypeScript and JSX code into standards-compliant web components with complete development toolchain.
75
Development server configuration and APIs for hot module replacement and live reloading. The Stencil dev server provides a complete development environment with file watching, automatic rebuilds, and browser synchronization.
Configuration options for the Stencil development server.
/**
* Development server configuration
*/
interface StencilDevServerConfig {
/** IP address for the dev server */
address?: string;
/** Base path for server routes */
basePath?: string;
/** Enable experimental dev modules bundling */
experimentalDevModules?: boolean;
/** Enable gzip compression */
gzip?: boolean;
/** HTTPS configuration */
https?: Credentials;
/** Initial URL to open */
initialLoadUrl?: string;
/** Log all requests to terminal */
logRequests?: boolean;
/** Open browser automatically */
openBrowser?: boolean;
/** Server port number */
port?: number;
/** Reload strategy for file changes */
reloadStrategy?: PageReloadStrategy;
/** Custom request listener file path */
requestListenerPath?: string;
/** Root directory to serve files from */
root?: string;
/** Enable server-side rendering */
ssr?: boolean;
/** Startup timeout in milliseconds */
startupTimeout?: number;
/** Enable websocket client */
websocket?: boolean;
/** Fork worker process for server */
worker?: boolean;
}
interface Credentials {
/** SSL private key */
key: string;
/** SSL certificate */
cert: string;
}
type PageReloadStrategy = 'hmr' | 'pageReload' | null;
/**
* Extended dev server configuration with internal options
*/
interface DevServerConfig extends StencilDevServerConfig {
/** Browser URL for opening */
browserUrl?: string;
/** Dev server working directory */
devServerDir?: string;
/** Glob patterns to exclude from HMR */
excludeHmr?: string[];
/** History API fallback configuration */
historyApiFallback?: HistoryApiFallback;
/** Prerender configuration file */
prerenderConfig?: string;
/** Protocol (http or https) */
protocol?: 'http' | 'https';
/** Source index.html file */
srcIndexHtml?: string;
/** Ping route for build status */
pingRoute?: string | null;
}
interface HistoryApiFallback {
/** Fallback index file */
index?: string;
/** Disable dot rule */
disableDotRule?: boolean;
}Usage Examples:
import { Config } from '@stencil/core';
export const config: Config = {
devServer: {
port: 3333,
address: '0.0.0.0',
openBrowser: true,
reloadStrategy: 'hmr',
logRequests: false,
gzip: true,
https: {
key: './ssl/server.key',
cert: './ssl/server.crt'
},
requestListenerPath: './dev-server-middleware.js'
}
};Runtime interface for the development server instance.
/**
* Development server runtime interface
*/
interface DevServer extends BuildEmitEvents {
/** Server address */
address: string;
/** Base path */
basePath: string;
/** Browser URL */
browserUrl: string;
/** Protocol used */
protocol: string;
/** Port number */
port: number;
/** Root directory */
root: string;
/** Close the server */
close(): Promise<void>;
}
/**
* Build event emitter interface
*/
interface BuildEmitEvents {
emit(eventName: 'fileAdd', path: string): void;
emit(eventName: 'fileDelete', path: string): void;
emit(eventName: 'fileUpdate', path: string): void;
emit(eventName: 'dirAdd', path: string): void;
emit(eventName: 'dirDelete', path: string): void;
emit(eventName: 'buildStart', buildStart: CompilerBuildStart): void;
emit(eventName: 'buildFinish', buildResults: CompilerBuildResults): void;
emit(eventName: 'buildNoChange', buildNoChange: BuildNoChangeResults): void;
emit(eventName: 'buildLog', buildLog: BuildLog): void;
emit(eventName: 'fsChange', fsWatchResults: FsWatchResults): void;
}HMR configuration and data structures for live reloading.
/**
* Hot module replacement data
*/
interface HotModuleReplacement {
/** Components that were updated */
componentsUpdated?: string[];
/** Files to exclude from HMR */
excludeHmr?: string[];
/** External stylesheets that were updated */
externalStylesUpdated?: string[];
/** Images that were updated */
imagesUpdated?: string[];
/** Whether index.html was updated */
indexHtmlUpdated?: boolean;
/** Inline styles that were updated */
inlineStylesUpdated?: HmrStyleUpdate[];
/** Reload strategy to use */
reloadStrategy: PageReloadStrategy;
/** Scripts that were added */
scriptsAdded?: string[];
/** Scripts that were deleted */
scriptsDeleted?: string[];
/** Whether service worker was updated */
serviceWorkerUpdated?: boolean;
/** Version ID for cache busting */
versionId?: string;
}
interface HmrStyleUpdate {
/** Style element ID */
styleId: string;
/** Complete style tag HTML */
styleTag: string;
/** Style text content */
styleText: string;
}Custom request handling for the development server.
/**
* Custom request listener function signature
* Used with requestListenerPath configuration
*/
type DevServerRequestListener = (
req: IncomingMessage,
res: ServerResponse,
next: () => void
) => void;Usage Example - Custom Middleware:
// dev-server-middleware.js
module.exports = function(req, res, next) {
// Handle API routes
if (req.url.startsWith('/api/')) {
if (req.url === '/api/health') {
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify({ status: 'ok', timestamp: Date.now() }));
return;
}
if (req.url === '/api/users') {
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify([
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]));
return;
}
// API not found
res.writeHead(404);
res.end('API endpoint not found');
return;
}
// Redirect old URLs
if (req.url === '/old-page') {
res.writeHead(301, { Location: '/new-page' });
res.end();
return;
}
// Add custom headers
res.setHeader('X-Dev-Server', 'Stencil');
// Pass to default handler
next();
};Events emitted by the development server for monitoring and integration.
/**
* Server event types
*/
type DevServerEventName =
| 'buildStart'
| 'buildFinish'
| 'buildLog'
| 'buildNoChange'
| 'fileAdd'
| 'fileUpdate'
| 'fileDelete'
| 'dirAdd'
| 'dirDelete'
| 'fsChange';
/**
* File system change event data
*/
interface FsWatchResults {
/** Directories that were added */
dirsAdded: string[];
/** Directories that were deleted */
dirsDeleted: string[];
/** Files that were updated */
filesUpdated: string[];
/** Files that were added */
filesAdded: string[];
/** Files that were deleted */
filesDeleted: string[];
}
/**
* Build log event data
*/
interface BuildLog {
/** Build identifier */
buildId: number;
/** Log messages */
messages: string[];
/** Build progress (0-1) */
progress: number;
}Client-side WebSocket API for communicating with the dev server.
/**
* WebSocket message types from dev server
*/
interface DevServerMessage {
/** Message type */
type: 'hmr-update' | 'build-start' | 'build-finish' | 'build-log' | 'reload';
/** Message data */
data?: any;
}
/**
* HMR update message data
*/
interface HmrUpdateMessage {
/** HMR data */
hmr: HotModuleReplacement;
/** Build results */
buildResults: CompilerBuildResults;
}Usage Example - WebSocket Integration:
// Client-side WebSocket handling
if ('WebSocket' in window) {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}`;
const ws = new WebSocket(wsUrl);
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
switch (message.type) {
case 'build-start':
console.log('Build started...');
showBuildStatus('Building...');
break;
case 'build-finish':
console.log('Build finished');
hideBuildStatus();
if (message.data.hasError) {
showBuildErrors(message.data.diagnostics);
}
break;
case 'hmr-update':
console.log('Hot module replacement update');
handleHmrUpdate(message.data.hmr);
break;
case 'reload':
console.log('Full page reload requested');
window.location.reload();
break;
case 'build-log':
console.log(`Build progress: ${message.data.progress * 100}%`);
updateBuildProgress(message.data.progress);
break;
}
};
ws.onopen = () => {
console.log('Connected to Stencil dev server');
};
ws.onclose = () => {
console.log('Disconnected from dev server');
setTimeout(() => {
// Attempt to reconnect
window.location.reload();
}, 1000);
};
}Development server performance and timing utilities.
/**
* Performance entry for dev server operations
*/
interface DevServerPerformanceEntry {
/** Operation name */
name: string;
/** Start time */
startTime: number;
/** Duration in milliseconds */
duration: number;
/** Additional details */
details?: { [key: string]: any };
}
/**
* Build timing information
*/
interface BuildTiming {
/** TypeScript compilation time */
tsc?: number;
/** Bundle generation time */
bundling?: number;
/** Asset processing time */
assets?: number;
/** Output generation time */
outputs?: number;
/** Total build time */
total: number;
}Support for editor integrations and development tools.
/**
* Editor configuration for development
*/
interface DevServerEditor {
/** Editor identifier */
id: string;
/** Display name */
name?: string;
/** Whether editor is supported */
supported?: boolean;
/** Priority for selection */
priority?: number;
}
/**
* Common editor configurations
*/
const EDITORS = {
VSCODE: { id: 'vscode', name: 'Visual Studio Code', priority: 1 },
WEBSTORM: { id: 'webstorm', name: 'WebStorm', priority: 2 },
SUBLIME: { id: 'sublime', name: 'Sublime Text', priority: 3 },
ATOM: { id: 'atom', name: 'Atom', priority: 4 }
};Usage Example - Advanced Dev Server Setup:
import { Config } from '@stencil/core';
export const config: Config = {
devServer: {
port: process.env.PORT ? parseInt(process.env.PORT) : 3333,
address: process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost',
openBrowser: process.env.CI !== 'true',
reloadStrategy: 'hmr',
// Advanced configuration
experimentalDevModules: true,
logRequests: process.env.DEBUG === 'true',
startupTimeout: 30000,
// Custom middleware for API mocking
requestListenerPath: './dev-middleware.js',
// HTTPS in development
https: process.env.HTTPS === 'true' ? {
key: './certificates/dev-key.pem',
cert: './certificates/dev-cert.pem'
} : undefined,
// Exclude certain patterns from HMR
excludeHmr: [
'**/test/**',
'**/*.spec.ts',
'**/*.e2e.ts'
]
},
// Watch additional directories
watchExternalDirs: [
'../shared-components/src',
'./design-tokens'
]
};Install with Tessl CLI
npx tessl i tessl/npm-stencil--coredocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10