or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# @web/dev-server-esbuild

1

2

@web/dev-server-esbuild is a plugin for @web/dev-server that integrates esbuild to transform TypeScript, JSX, TSX, and JavaScript files during development. It provides fast, efficient code transformation with automatic browser target detection and supports configurable compilation options.

3

4

## Package Information

5

6

- **Package Name**: @web/dev-server-esbuild

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @web/dev-server-esbuild`

10

- **Peer Dependencies**: Requires `@web/dev-server` or `@web/dev-server-core` for plugin integration

11

12

## Core Imports

13

14

The package exports a single function `esbuildPlugin`:

15

16

```typescript

17

import { esbuildPlugin } from "@web/dev-server-esbuild";

18

```

19

20

For CommonJS:

21

22

```javascript

23

const { esbuildPlugin } = require("@web/dev-server-esbuild");

24

```

25

26

**Note**: The package only exports the `esbuildPlugin` function. All types (`EsBuildPluginArgs`, `Plugin`, `Context`, etc.) are available for TypeScript users through the type definitions, but are not runtime exports.

27

28

## Basic Usage

29

30

```typescript

31

import { createConfig } from '@web/dev-server';

32

import { esbuildPlugin } from '@web/dev-server-esbuild';

33

34

export default createConfig({

35

plugins: [

36

// Basic TypeScript support

37

esbuildPlugin({ ts: true }),

38

39

// JSX support with custom factory

40

esbuildPlugin({

41

jsx: true,

42

jsxFactory: 'h',

43

jsxFragment: 'Fragment'

44

}),

45

46

// Multiple file types with auto targeting

47

esbuildPlugin({

48

ts: true,

49

tsx: true,

50

jsx: true,

51

target: 'auto'

52

})

53

]

54

});

55

```

56

57

## Capabilities

58

59

### Plugin Factory

60

61

Creates and configures an esbuild plugin instance for @web/dev-server.

62

63

```typescript { .api }

64

/**

65

* Creates an esbuild plugin instance for @web/dev-server

66

* @param args - Configuration options for the plugin

67

* @returns Plugin instance compatible with @web/dev-server

68

*/

69

function esbuildPlugin(args?: EsBuildPluginArgs): Plugin;

70

71

interface EsBuildPluginArgs {

72

/** Compilation target (e.g., 'es2020', 'auto', 'auto-always') or array of targets */

73

target?: string | string[];

74

/** Enable JavaScript compilation */

75

js?: boolean;

76

/** Enable TypeScript compilation */

77

ts?: boolean;

78

/** Enable JSON loading */

79

json?: boolean;

80

/** Enable JSX compilation */

81

jsx?: boolean;

82

/** Enable TSX compilation */

83

tsx?: boolean;

84

/** JSX factory function (e.g., 'React.createElement', 'h') */

85

jsxFactory?: string;

86

/** JSX fragment (e.g., 'React.Fragment', 'Fragment') */

87

jsxFragment?: string;

88

/** Custom file extension loaders */

89

loaders?: Record<string, Loader>;

90

/** Global constants replacement for define transforms */

91

define?: { [key: string]: string };

92

/** Path to TypeScript config file */

93

tsconfig?: string;

94

/** Code to prepend to all transformed files */

95

banner?: string;

96

/** Code to append to all transformed files */

97

footer?: string;

98

}

99

```

100

101

### Target Options

102

103

The `target` option controls compilation output:

104

105

- `'auto'` - Automatically detects browser capabilities from user agent. Skips compilation for modern browsers, falls back to ES module compatible code for older browsers

106

- `'auto-always'` - Similar to 'auto' but always compiles, using modern targets for recent browsers

107

- Specific targets like `'es2020'`, `'es2019'` - Compile to specific ECMAScript versions

108

- Array of browser targets like `['chrome80', 'firefox75', 'safari13']`

109

110

### File Type Support

111

112

Enable transformation for different file types:

113

114

```typescript

115

// TypeScript files (.ts)

116

esbuildPlugin({ ts: true })

117

118

// JSX files (.jsx)

119

esbuildPlugin({ jsx: true })

120

121

// TSX files (.tsx)

122

esbuildPlugin({ tsx: true })

123

124

// JSON files (.json)

125

esbuildPlugin({ json: true })

126

127

// JavaScript files (.js) - useful with custom targets

128

esbuildPlugin({ js: true, target: 'es2015' })

129

130

// Multiple types

131

esbuildPlugin({ ts: true, tsx: true, jsx: true, json: true })

132

```

133

134

### Custom Loaders

135

136

Configure how specific file extensions are processed:

137

138

```typescript

139

esbuildPlugin({

140

loaders: {

141

'.foo': 'text', // Load .foo files as text

142

'.bar': 'json', // Load .bar files as JSON

143

'scss': 'css' // Load .scss files as CSS (extension dot is optional)

144

}

145

})

146

```

147

148

### JSX Configuration

149

150

Customize JSX transformation:

151

152

```typescript

153

// React

154

esbuildPlugin({

155

jsx: true,

156

jsxFactory: 'React.createElement',

157

jsxFragment: 'React.Fragment'

158

})

159

160

// Preact

161

esbuildPlugin({

162

jsx: true,

163

jsxFactory: 'h',

164

jsxFragment: 'Fragment'

165

})

166

167

// Custom JSX

168

esbuildPlugin({

169

jsx: true,

170

jsxFactory: 'myCreateElement',

171

jsxFragment: 'myFragment'

172

})

173

```

174

175

### TypeScript Integration

176

177

Use with TypeScript configuration:

178

179

```typescript

180

esbuildPlugin({

181

ts: true,

182

tsconfig: './tsconfig.json' // Path to TypeScript config

183

})

184

```

185

186

### Code Transformation

187

188

Add code banners and footers:

189

190

```typescript

191

esbuildPlugin({

192

ts: true,

193

banner: '/* Generated code - do not edit */',

194

footer: '/* End of generated code */'

195

})

196

```

197

198

### Global Definitions

199

200

Replace global constants during compilation:

201

202

```typescript

203

esbuildPlugin({

204

ts: true,

205

define: {

206

'process.env.NODE_ENV': '"development"',

207

'__VERSION__': '"1.0.0"',

208

'DEBUG': 'true'

209

}

210

})

211

```

212

213

## Types

214

215

The following types are available when using TypeScript. Import them from their respective packages:

216

217

```typescript

218

// Main function and its configuration

219

import { esbuildPlugin } from '@web/dev-server-esbuild';

220

import type { EsBuildPluginArgs } from '@web/dev-server-esbuild';

221

222

// Plugin-related types from @web/dev-server-core

223

import type { Plugin, Context, PluginSyntaxError } from '@web/dev-server-core';

224

225

// esbuild types

226

import type { Loader } from 'esbuild';

227

```

228

229

```typescript { .api }

230

/** esbuild loader type for different file extensions (from 'esbuild') */

231

type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'dataurl' | 'file' | 'binary';

232

233

/** @web/dev-server plugin interface (imported from '@web/dev-server-core') */

234

interface Plugin {

235

name: string;

236

injectWebSocket?: boolean;

237

serverStart?(args: ServerStartParams): void | Promise<void>;

238

serverStop?(): void | Promise<void>;

239

serve?(context: Context): ServeResult | Promise<ServeResult>;

240

transform?(context: Context): TransformResult | Promise<TransformResult>;

241

transformCacheKey?(context: Context): string | undefined | Promise<string> | Promise<undefined>;

242

resolveImport?(args: {

243

source: string;

244

context: Context;

245

code?: string;

246

column?: number;

247

line?: number;

248

resolveOptions?: ResolveOptions;

249

}): ResolveResult | Promise<ResolveResult>;

250

resolveImportSkip?(context: Context, source: string, importer: string): void;

251

transformImport?(args: {

252

source: string;

253

context: Context;

254

code?: string;

255

column?: number;

256

line?: number;

257

}): ResolveResult | Promise<ResolveResult>;

258

resolveMimeType?(context: Context): ResolveMimeTypeResult | Promise<ResolveMimeTypeResult>;

259

fileParsed?(context: Context): void;

260

}

261

262

/** Server start parameters for plugin initialization */

263

interface ServerStartParams {

264

config: DevServerCoreConfig;

265

app: Koa;

266

server?: Server;

267

fileWatcher: FSWatcher;

268

logger: Logger;

269

webSockets?: WebSocketsManager;

270

}

271

272

/** Plugin method return types */

273

type ServeResult = void | string | { body: string; type?: string; headers?: Record<string, string> };

274

type TransformResult = void | string | { body?: string; headers?: Record<string, string>; transformCache?: boolean };

275

type ResolveResult = void | string | { id?: string };

276

type ResolveMimeTypeResult = void | string | { type?: string };

277

278

/** Resolve options for import resolution */

279

interface ResolveOptions {

280

isEntry?: boolean;

281

skipSelf?: boolean;

282

[key: string]: unknown;

283

}

284

285

/** Koa Context interface (imported from 'koa' package) */

286

interface Context {

287

/** Request URL path */

288

path: string;

289

/** Parsed URL object */

290

url: URL;

291

/** Request headers */

292

headers: Record<string, string>;

293

/** Request/Response body */

294

body: string | Buffer;

295

/** Response helpers */

296

response: {

297

/** Check if response matches a MIME type */

298

is(type: string): boolean;

299

};

300

/** Additional Koa context properties available but not commonly used by plugins */

301

}

302

303

/** Error thrown when plugin encounters syntax errors during transformation */

304

class PluginSyntaxError extends Error {

305

constructor(

306

public message: string,

307

public filePath: string,

308

public code: string,

309

public line: number,

310

public column: number,

311

);

312

}

313

```

314

315

## Advanced Usage

316

317

### Browser-Specific Targeting

318

319

The plugin automatically detects browser capabilities and adjusts compilation accordingly:

320

321

```typescript

322

// Automatic browser detection

323

esbuildPlugin({ target: 'auto', ts: true })

324

// - Modern Chrome/Firefox/Edge: compiles to 'esnext' (minimal transformation)

325

// - Latest Safari: compiles to Safari-specific target

326

// - Older browsers: compiles to ES module compatible code

327

```

328

329

### HTML Inline Script Transformation

330

331

The plugin automatically transforms inline scripts in HTML files:

332

333

```html

334

<script type="module">

335

// This TypeScript code will be transformed

336

const message: string = 'Hello, world!';

337

console.log(message);

338

</script>

339

```

340

341

### Import Resolution

342

343

For TypeScript files, the plugin handles `.js` import resolution by checking for corresponding `.ts` files:

344

345

```typescript

346

// In a .ts file, this import:

347

import { helper } from './utils.js';

348

// Will resolve to ./utils.ts if it exists

349

```

350

351

## Error Handling

352

353

The plugin provides detailed error information for compilation failures through the `PluginSyntaxError` class:

354

355

```typescript

356

// Example of syntax error thrown by the plugin

357

throw new PluginSyntaxError(

358

'Unexpected token', // Error message

359

'/path/to/file.ts', // File path where error occurred

360

'const x: invalid syntax;', // Code that caused the error

361

5, // Line number (1-based)

362

12 // Column number (1-based)

363

);

364

```

365

366

**Error Types:**

367

368

- **Syntax Errors**: Reports exact line and column numbers with code context via `PluginSyntaxError`

369

- **Type Errors**: Integrates with TypeScript configuration for type checking (when `tsconfig` is specified)

370

- **Build Failures**: Provides clear error messages from esbuild's internal error reporting

371

- **Warning Messages**: Non-fatal warnings are logged but don't stop transformation

372

373

**Common Error Scenarios:**

374

375

- Invalid TypeScript syntax in .ts/.tsx files

376

- Missing JSX factory configuration when using JSX without React

377

- Unsupported file extensions without proper loaders configured

378

- Malformed tsconfig.json files when `tsconfig` option is specified

379

- Invalid esbuild target specifications

380

381

**Error Handling Behavior:**

382

383

The plugin filters certain warnings (like "Unsupported source map comment") to reduce noise, but reports all compilation errors. Errors include detailed location information when available from esbuild.