or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

build-system.mdcli.mdconfiguration.mddevelopment-server.mdindex.mdplugins.mdutilities.md

development-server.mddocs/

0

# Development Server

1

2

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.

3

4

## Capabilities

5

6

### Server Management

7

8

Start and manage the development server instance with configuration options.

9

10

```typescript { .api }

11

/**

12

* Start the Snowpack development server

13

* @param commandOptions - Configuration and lockfile options

14

* @param options - Optional server configuration

15

* @returns Promise resolving to development server instance

16

*/

17

function startServer(

18

commandOptions: CommandOptions,

19

options?: {

20

isDev?: boolean;

21

isWatch?: boolean;

22

preparePackages?: boolean;

23

}

24

): Promise<SnowpackDevServer>;

25

```

26

27

```typescript

28

import { startServer, loadConfiguration } from "snowpack";

29

30

// Basic server startup

31

const config = await loadConfiguration();

32

const server = await startServer({ config });

33

34

// Server startup with lockfile

35

const lockfile = await loadLockfile(process.cwd());

36

const server = await startServer({ config, lockfile });

37

38

// Server startup with options

39

const server = await startServer({ config }, {

40

isDev: true,

41

isWatch: true,

42

preparePackages: true

43

});

44

45

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

46

```

47

48

### File Loading and Processing

49

50

Load and process files through the development server pipeline.

51

52

```typescript { .api }

53

/**

54

* Load a URL through the development server

55

* @param reqUrl - Request URL to load

56

* @param options - Optional load options

57

* @returns Promise resolving to load result or undefined

58

*/

59

loadUrl(reqUrl: string, options?: LoadUrlOptions): Promise<LoadResult<Buffer | string> | undefined>;

60

61

/**

62

* Load a URL with specific encoding

63

* @param reqUrl - Request URL to load

64

* @param options - Load options with encoding specification

65

* @returns Promise resolving to load result with specified encoding

66

*/

67

loadUrl(reqUrl: string, options: LoadUrlOptions & {encoding: BufferEncoding}): Promise<LoadResult<string> | undefined>;

68

69

/**

70

* Load a URL as buffer

71

* @param reqUrl - Request URL to load

72

* @param options - Load options with null encoding

73

* @returns Promise resolving to load result as buffer

74

*/

75

loadUrl(reqUrl: string, options: LoadUrlOptions & {encoding: null}): Promise<LoadResult<Buffer> | undefined>;

76

```

77

78

```typescript

79

// Load file as string

80

const result = await server.loadUrl('/src/app.js', { encoding: 'utf8' });

81

if (result) {

82

console.log('File contents:', result.contents);

83

console.log('Imports found:', result.imports);

84

}

85

86

// Load file for SSR

87

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

88

89

// Load file as buffer

90

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

91

```

92

93

### Request Handling

94

95

Handle HTTP requests and responses through the development server.

96

97

```typescript { .api }

98

/**

99

* Handle incoming HTTP requests

100

* @param req - HTTP request object

101

* @param res - HTTP response object

102

* @param options - Optional handling options

103

* @returns Promise resolving when request is handled

104

*/

105

handleRequest(req: http.IncomingMessage, res: http.ServerResponse, options?: {handleError?: boolean}): Promise<void>;

106

107

/**

108

* Send a file response

109

* @param req - HTTP request object

110

* @param res - HTTP response object

111

* @param result - Load result to send

112

*/

113

sendResponseFile(req: http.IncomingMessage, res: http.ServerResponse, result: LoadResult): void;

114

115

/**

116

* Send an error response

117

* @param req - HTTP request object

118

* @param res - HTTP response object

119

* @param status - HTTP status code

120

*/

121

sendResponseError(req: http.IncomingMessage, res: http.ServerResponse, status: number): void;

122

```

123

124

```typescript

125

import http from 'http';

126

127

// Create custom server using Snowpack handler

128

const customServer = http.createServer(async (req, res) => {

129

try {

130

await server.handleRequest(req, res);

131

} catch (error) {

132

await server.handleRequest(req, res, { handleError: true });

133

}

134

});

135

136

// Manual file serving

137

const result = await server.loadUrl(req.url);

138

if (result) {

139

server.sendResponseFile(req, res, result);

140

} else {

141

server.sendResponseError(req, res, 404);

142

}

143

```

144

145

### URL Resolution

146

147

Resolve file paths to URLs and package specifiers to URLs.

148

149

```typescript { .api }

150

/**

151

* Get URL for a file location

152

* @param fileLoc - File location path

153

* @returns File URL or null if not found

154

*/

155

getUrlForFile(fileLoc: string): string | null;

156

157

/**

158

* Get URL for a package specifier

159

* @param packageSpec - Package specifier (e.g., "react")

160

* @returns Promise resolving to package URL

161

*/

162

getUrlForPackage(packageSpec: string): Promise<string>;

163

```

164

165

```typescript

166

// Get URL for local file

167

const fileUrl = server.getUrlForFile('/src/components/Button.jsx');

168

// Result: "/src/components/Button.js"

169

170

// Get URL for npm package

171

const packageUrl = await server.getUrlForPackage('react');

172

// Result: "/web_modules/react.js"

173

```

174

175

### Server-Side Rendering

176

177

Get server runtime for executing modules server-side.

178

179

```typescript { .api }

180

/**

181

* Get server runtime for SSR

182

* @param options - Optional runtime options

183

* @returns Server runtime instance

184

*/

185

getServerRuntime(options?: {invalidateOnChange?: boolean}): ServerRuntime;

186

187

/**

188

* Server runtime for importing and executing modules server-side

189

*/

190

interface ServerRuntime {

191

/** Import a module server-side */

192

importModule<T = any>(url: string): Promise<ServerRuntimeModule<T>>;

193

/** Invalidate a cached module */

194

invalidateModule(url: string): void;

195

}

196

197

/**

198

* Server-side module wrapper

199

*/

200

interface ServerRuntimeModule<T extends any> {

201

/** Module exports */

202

exports: T;

203

/** Associated CSS files */

204

css: string[];

205

}

206

```

207

208

```typescript

209

// Get server runtime

210

const runtime = server.getServerRuntime({ invalidateOnChange: true });

211

212

// Import module server-side

213

const appModule = await runtime.importModule('/src/App.js');

214

const App = appModule.exports.default;

215

const cssFiles = appModule.css;

216

217

// Render component server-side

218

const html = renderToString(App());

219

220

// Invalidate cached module

221

runtime.invalidateModule('/src/App.js');

222

```

223

224

### File Watching

225

226

Monitor file changes during development.

227

228

```typescript { .api }

229

/**

230

* Register callback for file changes

231

* @param callback - Function to call when files change

232

*/

233

onFileChange(callback: OnFileChangeCallback): void;

234

235

/**

236

* Manually mark a file as changed

237

* @param fileLoc - File location that changed

238

*/

239

markChanged(fileLoc: string): void;

240

241

/**

242

* File change callback type

243

*/

244

type OnFileChangeCallback = ({filePath: string}) => any;

245

```

246

247

```typescript

248

// Register file change listener

249

server.onFileChange(({ filePath }) => {

250

console.log(`File changed: ${filePath}`);

251

// Perform custom handling

252

});

253

254

// Manually trigger file change

255

server.markChanged('/src/config.js');

256

```

257

258

### Server Lifecycle

259

260

Manage server shutdown and cleanup.

261

262

```typescript { .api }

263

/**

264

* Shutdown the development server

265

* @returns Promise resolving when server is shut down

266

*/

267

shutdown(): Promise<void>;

268

```

269

270

```typescript

271

// Graceful server shutdown

272

process.on('SIGINT', async () => {

273

console.log('Shutting down development server...');

274

await server.shutdown();

275

process.exit(0);

276

});

277

```

278

279

## Load Options

280

281

```typescript { .api }

282

/**

283

* Options for loading URLs through the development server

284

*/

285

interface LoadUrlOptions {

286

/** Server-side rendering mode */

287

isSSR?: boolean;

288

/** Hot module replacement mode */

289

isHMR?: boolean;

290

/** Module resolution mode */

291

isResolve?: boolean;

292

/** Allow stale cache */

293

allowStale?: boolean;

294

/** Response encoding */

295

encoding?: undefined | BufferEncoding | null;

296

/** Import map for resolution */

297

importMap?: ImportMap;

298

}

299

```

300

301

## Server Configuration

302

303

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

304

305

```typescript { .api }

306

/**

307

* Development server options

308

*/

309

interface DevOptions {

310

/** HTTPS configuration */

311

secure: boolean | {cert: string | Buffer; key: string | Buffer};

312

/** Server hostname */

313

hostname: string;

314

/** Server port */

315

port: number;

316

/** URL to open in browser */

317

openUrl?: string;

318

/** Browser to open */

319

open?: string;

320

/** Output mode */

321

output?: 'stream' | 'dashboard';

322

/** Enable hot module replacement */

323

hmr?: boolean;

324

/** HMR delay in milliseconds */

325

hmrDelay: number;

326

/** HMR port */

327

hmrPort: number | undefined;

328

/** Show HMR error overlay */

329

hmrErrorOverlay: boolean;

330

/** Tailwind config path */

331

tailwindConfig?: string;

332

}

333

```

334

335

```typescript

336

// Example server configuration

337

const config = createConfiguration({

338

devOptions: {

339

port: 3000,

340

hostname: 'localhost',

341

hmr: true,

342

hmrDelay: 0,

343

open: 'chrome',

344

output: 'dashboard'

345

}

346

});

347

348

const server = await startServer({ config });

349

```