or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdclient.mdhmr.mdindex.mdserver.mdsource-maps.mdutils.md

server.mddocs/

0

# Server Integration

1

2

Server-side integration with Vite that handles module transformation, resolution, and caching through Vite's plugin system. The server component provides the bridge between Vite's transformation pipeline and the Node.js runtime execution.

3

4

## Capabilities

5

6

### ViteNodeServer

7

8

Main server class that integrates with Vite's development server to provide module transformation and resolution services.

9

10

```typescript { .api }

11

/**

12

* Main server class for integrating with Vite's development server

13

* Handles module transformation, resolution, caching, and externalization

14

*/

15

class ViteNodeServer {

16

constructor(server: ViteDevServer, options?: ViteNodeServerOptions);

17

18

/** Fetch and transform a module for execution */

19

fetchModule(id: string, transformMode?: 'web' | 'ssr'): Promise<FetchResult>;

20

21

/** Resolve a module ID using Vite's resolution system */

22

resolveId(id: string, importer?: string, transformMode?: 'web' | 'ssr'): Promise<ViteNodeResolveId | null>;

23

24

/** Get source map for a transformed module */

25

getSourceMap(source: string): EncodedSourceMap | null;

26

27

/** Check if a module should be externalized (not transformed) */

28

shouldExternalize(id: string): Promise<string | false>;

29

30

/** Get total transformation duration for performance monitoring */

31

getTotalDuration(): number;

32

33

/** Transform a module request */

34

transformRequest(id: string, filepath?: string, transformMode?: 'web' | 'ssr'): Promise<TransformResult | null | undefined>;

35

36

/** Transform a module for web mode only */

37

transformModule(id: string, transformMode?: 'web' | 'ssr'): Promise<{ code: string | undefined }>;

38

39

/** Determine the transform mode for a given module */

40

getTransformMode(id: string): 'ssr' | 'web';

41

42

// Properties

43

server: ViteDevServer;

44

options: ViteNodeServerOptions;

45

fetchCache: Map<string, FetchCache>;

46

externalizeCache: Map<string, Promise<string | false>>;

47

debugger?: Debugger;

48

}

49

50

interface ViteNodeServerOptions {

51

/** Source map handling mode */

52

sourcemap?: 'inline' | boolean;

53

54

/** Dependency handling configuration */

55

deps?: DepsHandlingOptions;

56

57

/** Transform mode configuration for different file patterns */

58

transformMode?: {

59

ssr?: RegExp[];

60

web?: RegExp[];

61

};

62

63

/** Debug options */

64

debug?: DebuggerOptions;

65

}

66

67

interface FetchResult {

68

/** Transformed code */

69

code?: string;

70

71

/** External module path if module should be externalized */

72

externalize?: string;

73

74

/** Source map for the transformed code */

75

map?: EncodedSourceMap | null;

76

}

77

78

interface ViteNodeResolveId {

79

/** Whether module is external */

80

external?: boolean | 'absolute' | 'relative';

81

82

/** Resolved module ID */

83

id: string;

84

85

/** Additional metadata */

86

meta?: Record<string, any> | null;

87

88

/** Module side effects configuration */

89

moduleSideEffects?: boolean | 'no-treeshake' | null;

90

91

/** Synthetic named exports configuration */

92

syntheticNamedExports?: boolean | string | null;

93

}

94

```

95

96

**Usage Examples:**

97

98

```typescript

99

import { createServer } from "vite";

100

import { ViteNodeServer } from "vite-node/server";

101

102

// Create Vite development server

103

const viteServer = await createServer({

104

server: { hmr: true },

105

});

106

107

// Create vite-node server

108

const nodeServer = new ViteNodeServer(viteServer, {

109

sourcemap: 'inline',

110

deps: {

111

inline: ['my-package'],

112

external: ['heavy-dependency'],

113

},

114

});

115

116

// Fetch and transform a module

117

const result = await nodeServer.fetchModule('./src/app.ts');

118

119

// Resolve a module ID

120

const resolved = await nodeServer.resolveId('./utils', './src/app.ts');

121

````

122

123

### Dependency Handling

124

125

Configuration for how dependencies should be handled during transformation.

126

127

```typescript { .api }

128

/**

129

* Configuration for dependency handling during module transformation

130

* Controls which modules are inlined vs externalized

131

*/

132

interface DepsHandlingOptions {

133

/** Dependencies that should always be externalized (not transformed) */

134

external?: (string | RegExp)[];

135

136

/** Dependencies that should be inlined (transformed), or true for all */

137

inline?: (string | RegExp)[] | true;

138

139

/** Specific files that should be inlined by file path */

140

inlineFiles?: string[];

141

142

/** Directories considered to hold Node.js modules */

143

moduleDirectories?: string[];

144

145

/** Cache directory for dependency resolution */

146

cacheDir?: string;

147

148

/** Try to guess the CJS version of a package when it's invalid ESM */

149

fallbackCJS?: boolean;

150

}

151

```

152

153

**Usage Examples:**

154

155

```typescript

156

const serverOptions = {

157

deps: {

158

// Always externalize these packages

159

external: ['lodash', /^@types\//],

160

161

// Inline these packages for transformation

162

inline: ['my-esm-package', /^@my-org\//],

163

164

// Inline specific files

165

inlineFiles: ['/path/to/specific/file.js'],

166

167

// Custom module directories

168

moduleDirectories: ['/node_modules/', '/custom_modules/'],

169

170

// Enable CJS fallback

171

fallbackCJS: true,

172

},

173

};

174

```

175

176

### Transform Mode Configuration

177

178

Configure which files should be transformed in 'web' vs 'ssr' mode.

179

180

```typescript { .api }

181

/**

182

* Transform mode configuration for different file patterns

183

* Determines whether files are processed as web or SSR modules

184

*/

185

interface TransformModeOptions {

186

/** RegExp patterns for files that should use SSR transformation */

187

ssr?: RegExp[];

188

189

/** RegExp patterns for files that should use web transformation */

190

web?: RegExp[];

191

}

192

```

193

194

**Usage Examples:**

195

196

```typescript

197

const serverOptions = {

198

transformMode: {

199

// Process Vue SFCs in web mode

200

web: [/\.vue$/],

201

202

// Process server utilities in SSR mode

203

ssr: [/\/server\//, /\.server\./],

204

},

205

};

206

```

207

208

### Debug Options

209

210

Configuration for debugging and development features.

211

212

```typescript { .api }

213

/**

214

* Debug configuration options for development and troubleshooting

215

* Enables module dumping and loading for debugging transformed code

216

*/

217

interface DebuggerOptions {

218

/** Dump transformed modules to filesystem for inspection */

219

dumpModules?: boolean | string;

220

221

/** Load dumped modules from filesystem instead of transforming */

222

loadDumppedModules?: boolean;

223

}

224

```

225

226

**Usage Examples:**

227

228

```typescript

229

const serverOptions = {

230

debug: {

231

// Dump to default .vite-node/dump directory

232

dumpModules: true,

233

234

// Or dump to custom directory

235

dumpModules: './debug-output',

236

237

// Load from dumped files for debugging

238

loadDumppedModules: process.env.NODE_ENV === 'debug',

239

},

240

};

241

```

242

243

### Externalization

244

245

Control which modules should be externalized (not transformed by Vite).

246

247

```typescript { .api }

248

/**

249

* Check if a module should be externalized (not transformed)

250

* Returns the external module path or false if should be inlined

251

*/

252

function shouldExternalize(

253

id: string,

254

options?: DepsHandlingOptions,

255

cache?: Map<string, Promise<string | false>>

256

): Promise<string | false>;

257

258

/**

259

* Attempt to find a CommonJS version of an ESM module

260

* Useful when fallbackCJS is enabled and ESM module is invalid

261

*/

262

function guessCJSversion(id: string): string | undefined;

263

```

264

265

**Usage Examples:**

266

267

```typescript

268

import { shouldExternalize, guessCJSversion } from "vite-node/server";

269

270

// Check if module should be externalized

271

const external = await shouldExternalize('lodash');

272

if (external) {

273

// Module will be externalized, use external path

274

console.log(`Externalizing: ${external}`);

275

} else {

276

// Module will be inlined and transformed

277

console.log('Inlining module');

278

}

279

280

// Try to find CJS version of ESM module

281

const cjsVersion = guessCJSversion('/node_modules/package/es/index.js');

282

if (cjsVersion) {

283

console.log(`Found CJS alternative: ${cjsVersion}`);

284

}

285

```

286

287

## Performance and Caching

288

289

The server includes sophisticated caching mechanisms:

290

291

- **Transform Cache**: Caches transformation results per transform mode

292

- **Fetch Cache**: Caches complete fetch results including metadata

293

- **Externalize Cache**: Caches externalization decisions

294

- **Duration Tracking**: Performance monitoring for transformation times

295

296

```typescript

297

// Access performance data

298

const totalDuration = nodeServer.getTotalDuration();

299

console.log(`Total transformation time: ${totalDuration}ms`);

300

```

301

302

## Error Handling

303

304

The server handles various error conditions during transformation:

305

306

- **Module Resolution Failures**: When modules cannot be resolved

307

- **Transformation Errors**: Syntax errors or plugin failures during transformation

308

- **Cache Misses**: Fallback handling when cached modules are invalid

309

- **External Module Loading**: Errors when loading externalized dependencies

310

311

Common error handling patterns:

312

313

```typescript

314

try {

315

const result = await nodeServer.fetchModule('./problematic-module.ts');

316

} catch (error) {

317

if (error.message.includes('Failed to load url')) {

318

// Handle module loading failure

319

} else {

320

// Handle transformation error

321

}

322

}

323

```