or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Rollup Plugin Serve

1

2

Rollup Plugin Serve is a development server plugin for Rollup that serves bundled files during development, similar to webpack-dev-server. It provides static file serving with features like HTTPS support, history API fallback, custom headers, MIME types, and browser auto-opening.

3

4

## Package Information

5

6

- **Package Name**: rollup-plugin-serve

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install --save-dev rollup-plugin-serve`

10

11

## Core Imports

12

13

```javascript

14

import serve from "rollup-plugin-serve";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const serve = require("rollup-plugin-serve");

21

```

22

23

## Basic Usage

24

25

```javascript

26

// rollup.config.js

27

import serve from "rollup-plugin-serve";

28

29

export default {

30

input: "src/main.js",

31

output: {

32

file: "dist/bundle.js",

33

format: "cjs"

34

},

35

plugins: [

36

serve("dist") // Serve files from dist directory

37

]

38

};

39

```

40

41

## Architecture

42

43

The plugin creates an HTTP/HTTPS server during Rollup's build process and integrates with Rollup's plugin system through the `generateBundle` hook. Key components include:

44

45

- **Server Management**: Handles HTTP/HTTPS server lifecycle, including graceful restart on configuration changes

46

- **Static File Serving**: Serves files from configurable content directories with path traversal protection

47

- **History API Support**: SPA-friendly fallback routing for client-side routing applications

48

- **MIME Type Handling**: Extensible MIME type detection and custom type registration

49

- **Development Features**: Browser auto-opening, verbose logging, and custom header injection

50

51

## Capabilities

52

53

### Plugin Function

54

55

Creates a Rollup plugin instance that provides development server functionality.

56

57

```javascript { .api }

58

/**

59

* Serve your rolled up bundle like webpack-dev-server

60

* @param options - Configuration options, string shorthand for contentBase, or array of contentBase paths

61

* @returns Rollup plugin object

62

*/

63

function serve(options?: RollupServeOptions | string | string[]): Plugin;

64

65

**Shorthand Usage:**

66

67

```javascript

68

// String shorthand for contentBase

69

serve("public");

70

71

// Array shorthand for multiple contentBase paths

72

serve(["dist", "static"]);

73

```

74

75

**Advanced Configuration:**

76

77

```javascript

78

serve({

79

contentBase: ["dist", "static"],

80

port: 3000,

81

host: "0.0.0.0",

82

open: true,

83

openPage: "/dashboard",

84

historyApiFallback: true,

85

https: {

86

key: fs.readFileSync("server.key"),

87

cert: fs.readFileSync("server.crt")

88

},

89

headers: {

90

"Access-Control-Allow-Origin": "*",

91

"Cache-Control": "no-cache"

92

},

93

mimeTypes: {

94

"application/javascript": ["js_proxy"]

95

},

96

onListening: (server) => {

97

const address = server.address();

98

console.log(`Server running at http://localhost:${address.port}`);

99

}

100

});

101

```

102

103

### Configuration Options

104

105

Complete configuration interface for the serve plugin.

106

107

```javascript { .api }

108

interface RollupServeOptions {

109

/** Launch browser after first bundle is generated (default: false) */

110

open?: boolean;

111

112

/**

113

* Page to open when browser launches. Must start with '/'.

114

* Only used when open=true (default: '')

115

*/

116

openPage?: string;

117

118

/** Show server address in console (default: true) */

119

verbose?: boolean;

120

121

/**

122

* Folder(s) to serve static files from.

123

* Supports string or array of strings (default: current directory)

124

*/

125

contentBase?: string | string[];

126

127

/**

128

* Return index.html (200) instead of 404 for SPA routing.

129

* Use true for default '/index.html' or string for custom fallback path

130

*/

131

historyApiFallback?: boolean | string;

132

133

/** Server host address (default: 'localhost') */

134

host?: string;

135

136

/** Server port number (default: 10001) */

137

port?: number | string;

138

139

/** HTTPS server configuration from Node.js https module */

140

https?: ServerOptions;

141

142

/** Custom HTTP response headers */

143

headers?: IncomingHttpHeaders | OutgoingHttpHeaders | {

144

[name: string]: number | string | ReadonlyArray<string>;

145

};

146

147

/** Custom MIME type definitions using mime package format */

148

mimeTypes?: TypeMap;

149

150

/** Callback executed after server begins listening */

151

onListening?: (server: Server) => void;

152

}

153

```

154

155

### Content Base Configuration

156

157

The `contentBase` option supports multiple patterns for serving static files:

158

159

```javascript

160

// Single directory

161

serve({ contentBase: "dist" });

162

163

// Multiple directories (fallback order)

164

serve({ contentBase: ["dist", "public", "assets"] });

165

166

// Current directory (default)

167

serve({ contentBase: "" });

168

```

169

170

When multiple content bases are specified, the server attempts to serve files from each directory in order until a file is found.

171

172

### History API Fallback

173

174

For single-page applications with client-side routing:

175

176

```javascript

177

// Default fallback to /index.html

178

serve({ historyApiFallback: true });

179

180

// Custom fallback page

181

serve({ historyApiFallback: "/app.html" });

182

183

// Conditional fallback with contentBase priority

184

serve({

185

contentBase: ["dist", "public"],

186

historyApiFallback: "/fallback.html"

187

});

188

```

189

190

### HTTPS Configuration

191

192

Enable HTTPS with SSL/TLS certificates:

193

194

```javascript

195

import fs from "fs";

196

197

serve({

198

https: {

199

key: fs.readFileSync("path/to/private-key.pem"),

200

cert: fs.readFileSync("path/to/certificate.pem"),

201

ca: fs.readFileSync("path/to/ca-certificate.pem") // Optional

202

},

203

port: 443

204

});

205

```

206

207

### Custom Headers

208

209

Set response headers for all served files:

210

211

```javascript

212

serve({

213

headers: {

214

"Access-Control-Allow-Origin": "*",

215

"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",

216

"Cache-Control": "no-cache, no-store, must-revalidate",

217

"X-Custom-Header": "development-server"

218

}

219

});

220

```

221

222

### MIME Type Configuration

223

224

Define custom MIME types for file extensions:

225

226

```javascript

227

serve({

228

mimeTypes: {

229

"application/javascript": ["js_commonjs-proxy", "js_module"],

230

"text/x-custom": ["custom", "cst"],

231

"application/wasm": ["wasm"]

232

}

233

});

234

```

235

236

### Server Lifecycle Callbacks

237

238

Handle server events and customize behavior:

239

240

```javascript

241

serve({

242

onListening: function(server) {

243

const address = server.address();

244

const protocol = this.https ? "https" : "http";

245

const host = address.address === "::" ? "localhost" : address.address;

246

247

console.log(`๐Ÿš€ Server ready at ${protocol}://${host}:${address.port}`);

248

249

// Access plugin options via 'this'

250

if (this.verbose) {

251

console.log("Serving from:", this.contentBase);

252

}

253

}

254

});

255

```

256

257

## Types

258

259

```javascript { .api }

260

// From Node.js net module (used by http.Server)

261

interface AddressInfo {

262

address: string;

263

family: string;

264

port: number;

265

}

266

267

// From Node.js http module

268

interface Server {

269

listen(port: number, host?: string, callback?: () => void): void;

270

close(callback?: () => void): void;

271

address(): AddressInfo | string | null;

272

on(event: string, listener: Function): void;

273

}

274

275

// From Node.js https module

276

interface ServerOptions {

277

key?: string | Buffer | Array<string | Buffer>;

278

cert?: string | Buffer | Array<string | Buffer>;

279

ca?: string | Buffer | Array<string | Buffer>;

280

// Additional HTTPS options...

281

}

282

283

// From Node.js http module

284

interface IncomingHttpHeaders {

285

[header: string]: string | string[] | undefined;

286

}

287

288

interface OutgoingHttpHeaders {

289

[header: string]: number | string | string[] | undefined;

290

}

291

292

// From mime package

293

interface TypeMap {

294

[mimeType: string]: string[];

295

}

296

297

// Rollup Plugin interface

298

interface Plugin {

299

name: string;

300

generateBundle?: () => void;

301

}

302

303

// Server Error interface (Node.js)

304

interface ServerError extends Error {

305

code?: string;

306

errno?: number;

307

syscall?: string;

308

address?: string;

309

port?: number;

310

}

311

```

312

313

## Error Handling

314

315

The plugin handles common server errors automatically:

316

317

- **Port in use (EADDRINUSE)**: Logs error message and exits process with `process.exit()`

318

- **File not found (ENOENT)**: Returns 404 with descriptive error page showing file path

319

- **Server errors**: Returns 500 with error details, file path, and plugin identifier

320

- **Path traversal attempts**: Uses `posix.normalize()` to prevent directory traversal attacks

321

322

Common error scenarios:

323

324

```javascript

325

// Error handling is automatic, but you can detect port conflicts:

326

serve({

327

port: 8080,

328

onListening: (server) => {

329

console.log("Server started successfully");

330

}

331

});

332

333

// If port 8080 is in use, the plugin will log:

334

// "http://localhost:8080 is in use, either stop the other server or use a different port."

335

```