or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Webpack Hot Middleware

1

2

Webpack Hot Middleware provides webpack hot module replacement (HMR) for custom server setups without requiring webpack-dev-server. It acts as a bridge between webpack's compilation process and browser clients using Server-Sent Events to communicate build updates and coordinate hot module replacement through webpack's HMR API.

3

4

## Package Information

5

6

- **Package Name**: webpack-hot-middleware

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install --save-dev webpack-hot-middleware`

10

11

## Core Imports

12

13

```javascript

14

const webpackHotMiddleware = require("webpack-hot-middleware");

15

```

16

17

For client-side integration:

18

19

```javascript

20

// In webpack entry configuration

21

entry: {

22

main: ['webpack-hot-middleware/client', './src/main.js']

23

}

24

```

25

26

## Basic Usage

27

28

```javascript

29

const webpack = require('webpack');

30

const express = require('express');

31

const webpackDevMiddleware = require('webpack-dev-middleware');

32

const webpackHotMiddleware = require('webpack-hot-middleware');

33

34

const app = express();

35

const config = require('./webpack.config.js');

36

const compiler = webpack(config);

37

38

// Add webpack-dev-middleware

39

app.use(webpackDevMiddleware(compiler, {

40

publicPath: config.output.publicPath

41

}));

42

43

// Add webpack-hot-middleware

44

app.use(webpackHotMiddleware(compiler));

45

46

app.listen(3000);

47

```

48

49

## Architecture

50

51

Webpack Hot Middleware operates through several key components:

52

53

- **Server Middleware**: Express/Connect-compatible middleware that manages webpack compiler events and client connections

54

- **Event Stream**: Server-Sent Events (SSE) communication layer for real-time updates between server and clients

55

- **Client Runtime**: Browser-side JavaScript that connects to the event stream and applies HMR updates

56

- **Error Overlay**: Optional browser overlay displaying compilation errors and warnings

57

- **Update Processing**: Module update detection and application using webpack's HMR API

58

59

## Capabilities

60

61

### Server Middleware

62

63

The main middleware factory function that creates HMR middleware for a webpack compiler.

64

65

```javascript { .api }

66

/**

67

* Creates webpack hot middleware for a compiler instance

68

* @param {Object} compiler - webpack compiler instance

69

* @param {Object} opts - Configuration options

70

* @returns {Function} Express/Connect-compatible middleware with additional methods

71

*/

72

function webpackHotMiddleware(compiler, opts);

73

74

interface MiddlewareOptions {

75

/** Function for logging or false to disable (default: console.log) */

76

log?: Function | false;

77

/** Path for event stream endpoint (default: '/__webpack_hmr') */

78

path?: string;

79

/** Heartbeat interval in milliseconds (default: 10000) */

80

heartbeat?: number;

81

/** Stats configuration object (default: {}) */

82

statsOptions?: Object;

83

}

84

```

85

86

The middleware function includes additional methods:

87

88

```javascript { .api }

89

interface MiddlewareInstance {

90

/** Manually publish events to connected clients */

91

publish(payload: Object): void;

92

/** Close the middleware and clean up resources */

93

close(): void;

94

}

95

```

96

97

**Usage Example:**

98

99

```javascript

100

const webpackHotMiddleware = require('webpack-hot-middleware');

101

102

// Basic usage

103

const hotMiddleware = webpackHotMiddleware(compiler);

104

app.use(hotMiddleware);

105

106

// With options

107

const hotMiddleware = webpackHotMiddleware(compiler, {

108

log: console.log,

109

path: '/__webpack_hmr',

110

heartbeat: 10 * 1000

111

});

112

app.use(hotMiddleware);

113

114

// Manual event publishing

115

hotMiddleware.publish({

116

action: 'reload'

117

});

118

119

// Cleanup

120

hotMiddleware.close();

121

```

122

123

### Client Integration

124

125

Client-side module that connects to the HMR server and handles module updates.

126

127

```javascript { .api }

128

/**

129

* Client module exports when used as CommonJS module

130

*/

131

interface ClientExports {

132

/** Subscribe to all HMR events */

133

subscribeAll(handler: Function): void;

134

/** Subscribe to custom HMR events */

135

subscribe(handler: Function): void;

136

/** Replace default error overlay with custom implementation */

137

useCustomOverlay(customOverlay: Object): void;

138

/** Set client options and establish connection */

139

setOptionsAndConnect(overrides: Object): void;

140

}

141

```

142

143

**Usage Examples:**

144

145

```javascript

146

// As webpack entry (automatic connection)

147

entry: {

148

main: ['webpack-hot-middleware/client', './src/main.js']

149

}

150

151

// As module for custom handling

152

const client = require('webpack-hot-middleware/client');

153

154

client.subscribe(function(obj) {

155

if (obj.action === 'reload') {

156

window.location.reload();

157

}

158

});

159

160

client.subscribeAll(function(obj) {

161

console.log('HMR event:', obj);

162

});

163

```

164

165

### Client Configuration

166

167

Client behavior can be configured via query parameters when including in webpack entry.

168

169

```javascript { .api }

170

interface ClientOptions {

171

/** Event stream endpoint path (default: '/__webpack_hmr') */

172

path?: string;

173

/** Bundle name for multi-compiler mode */

174

name?: string;

175

/** Reconnection timeout in milliseconds (default: 20000) */

176

timeout?: number;

177

/** Enable/disable error overlay (default: true) */

178

overlay?: boolean;

179

/** Enable auto-reload on webpack stuck (default: false) */

180

reload?: boolean;

181

/** Disable informational logging (default: false) */

182

noInfo?: boolean;

183

/** Disable all console logging (default: false) */

184

quiet?: boolean;

185

/** Use webpack publicPath as path prefix (default: false) */

186

dynamicPublicPath?: boolean;

187

/** Auto-connect to server (default: true) */

188

autoConnect?: boolean;

189

/** Custom ANSI colors for overlay */

190

ansiColors?: Object;

191

/** Custom styles for error overlay */

192

overlayStyles?: Object;

193

/** Show overlay for warnings (default: false) */

194

overlayWarnings?: boolean;

195

}

196

```

197

198

**Configuration Examples:**

199

200

```javascript

201

// Basic client configuration

202

entry: {

203

main: [

204

'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true',

205

'./src/main.js'

206

]

207

}

208

209

// Multi-compiler configuration

210

module.exports = [

211

{

212

name: 'mobile',

213

entry: {

214

main: ['webpack-hot-middleware/client?name=mobile', 'mobile.js']

215

}

216

},

217

{

218

name: 'desktop',

219

entry: {

220

main: ['webpack-hot-middleware/client?name=desktop', 'desktop.js']

221

}

222

}

223

];

224

225

// Custom overlay colors and styles

226

const ansiColors = { red: '00FF00' };

227

const overlayStyles = { color: '#FF0000' };

228

const clientScript = 'webpack-hot-middleware/client?ansiColors=' +

229

encodeURIComponent(JSON.stringify(ansiColors)) +

230

'&overlayStyles=' + encodeURIComponent(JSON.stringify(overlayStyles));

231

```

232

233

### Error Overlay

234

235

Browser overlay system for displaying compilation errors and warnings.

236

237

```javascript { .api }

238

/**

239

* Creates customizable error overlay for browser

240

* @param {Object} options - Configuration with ansiColors and overlayStyles

241

* @returns {Object} Overlay instance with control methods

242

*/

243

function createOverlay(options: OverlayOptions): OverlayInstance;

244

245

interface OverlayOptions {

246

/** Custom ANSI color mappings */

247

ansiColors?: Object;

248

/** Custom CSS styles for overlay element */

249

overlayStyles?: Object;

250

}

251

252

interface OverlayInstance {

253

/** Display compilation problems in overlay */

254

showProblems(type: 'errors' | 'warnings', lines: string[]): void;

255

/** Remove overlay from DOM */

256

clear(): void;

257

}

258

```

259

260

**Usage Example:**

261

262

```javascript

263

const createOverlay = require('webpack-hot-middleware/client-overlay');

264

265

const overlay = createOverlay({

266

ansiColors: {

267

red: 'ff0000',

268

yellow: 'ffff00'

269

},

270

overlayStyles: {

271

fontSize: '14px',

272

fontFamily: 'Monaco, monospace'

273

}

274

});

275

276

// Show errors

277

overlay.showProblems('errors', [

278

'Module not found: Error: Cannot resolve module "missing-module"'

279

]);

280

281

// Clear overlay

282

overlay.clear();

283

```

284

285

### Helper Utilities

286

287

Utility functions used internally by the middleware.

288

289

```javascript { .api }

290

/**

291

* URL path matching utility

292

* @param {string} url - URL string to test

293

* @param {string} path - Path string to match against

294

* @returns {boolean} True if paths match

295

*/

296

function pathMatch(url: string, path: string): boolean;

297

```

298

299

## Event Protocol

300

301

The middleware communicates with clients using a defined event protocol over Server-Sent Events.

302

303

### Server to Client Events

304

305

```javascript { .api }

306

interface HMREvent {

307

/** Event action type */

308

action: 'building' | 'built' | 'sync';

309

/** Bundle name (for multi-compiler) */

310

name?: string;

311

/** Build completion time in milliseconds */

312

time?: number;

313

/** Build hash string */

314

hash?: string;

315

/** Compilation warnings */

316

warnings?: string[];

317

/** Compilation errors */

318

errors?: string[];

319

/** Module ID to name mapping */

320

modules?: Object;

321

}

322

```

323

324

### Event Types

325

326

- **building**: Emitted when webpack starts rebuilding

327

- **built**: Emitted when webpack completes a build

328

- **sync**: Emitted when a client first connects to sync current state

329

330

## Multi-Compiler Support

331

332

Webpack Hot Middleware supports webpack's multi-compiler mode for handling multiple webpack configurations simultaneously.

333

334

**Configuration:**

335

336

```javascript

337

// webpack.config.js

338

module.exports = [

339

{

340

name: 'client',

341

entry: {

342

main: ['webpack-hot-middleware/client?name=client', './src/client.js']

343

},

344

// ... other client config

345

},

346

{

347

name: 'server',

348

entry: {

349

main: ['webpack-hot-middleware/client?name=server', './src/server.js']

350

},

351

// ... other server config

352

}

353

];

354

355

// Server setup

356

const compiler = webpack(configs);

357

app.use(webpackHotMiddleware(compiler));

358

```

359

360

## Error Handling

361

362

The middleware handles various error conditions and provides fallback mechanisms:

363

364

- **Connection Loss**: Automatic reconnection with configurable timeout

365

- **Build Errors**: Error overlay display with ANSI color support

366

- **Update Failures**: Fallback to full page reload when HMR fails

367

- **Module Rejection**: Graceful handling of modules that can't be hot updated

368

369

## Webpack Configuration

370

371

Required webpack configuration for hot module replacement:

372

373

```javascript

374

// webpack.config.js

375

const webpack = require('webpack');

376

377

module.exports = {

378

plugins: [

379

new webpack.HotModuleReplacementPlugin()

380

],

381

entry: {

382

main: ['webpack-hot-middleware/client', './src/main.js']

383

}

384

};

385

```