or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-compilation.mdcompilation.mdconfiguration.mdexpress-integration.mdindex.mdrendering.md

client-compilation.mddocs/

0

# Client-Side Compilation

1

2

Browser-compatible template compilation for client-side rendering. These functions generate standalone JavaScript code that can run in browsers without Node.js dependencies, enabling dynamic template rendering on the client side.

3

4

## Capabilities

5

6

### Compile Client Function

7

8

Compiles a Pug template to JavaScript source code for browser execution.

9

10

```javascript { .api }

11

/**

12

* Compile template to JavaScript source for browser use

13

* @param str - Pug template source code

14

* @param options - Client compilation options

15

* @returns JavaScript source code string

16

*/

17

function compileClient(str, options);

18

```

19

20

**Usage Examples:**

21

22

```javascript

23

const pug = require('pug');

24

25

// Basic client compilation

26

const clientJS = pug.compileClient('p Hello #{name}!');

27

console.log(clientJS);

28

// Output: function template(locals) { ... return "<p>Hello " + pug.escape(locals.name) + "!</p>"; }

29

30

// With options

31

const clientJS2 = pug.compileClient(`

32

div.user-card

33

h3= user.name

34

p= user.email

35

if user.verified

36

span.badge Verified

37

`, {

38

name: 'userCardTemplate',

39

compileDebug: false,

40

inlineRuntimeFunctions: true

41

});

42

43

// Save to file for browser use

44

const fs = require('fs');

45

fs.writeFileSync('templates/user-card.js', clientJS2);

46

```

47

48

### Compile File Client Function

49

50

Compiles a Pug template file to JavaScript source code with caching support.

51

52

```javascript { .api }

53

/**

54

* Compile template file to client-side JavaScript

55

* @param path - Path to Pug template file

56

* @param options - Client compilation options

57

* @returns JavaScript source code string with caching

58

*/

59

function compileFileClient(path, options);

60

```

61

62

**Usage Examples:**

63

64

```javascript

65

const pug = require('pug');

66

67

// Compile file to client JavaScript

68

const clientJS = pug.compileFileClient('./templates/product-list.pug', {

69

name: 'productListTemplate',

70

inlineRuntimeFunctions: false

71

});

72

73

// With caching for build processes

74

const clientJS2 = pug.compileFileClient('./templates/modal.pug', {

75

cache: true,

76

name: 'modalTemplate',

77

compileDebug: false

78

});

79

80

// Build step: compile all templates

81

const templates = [

82

'user-profile.pug',

83

'product-card.pug',

84

'navigation.pug'

85

];

86

87

templates.forEach(template => {

88

const js = pug.compileFileClient(`./src/templates/${template}`, {

89

name: template.replace('.pug', 'Template'),

90

inlineRuntimeFunctions: true

91

});

92

93

fs.writeFileSync(`./dist/templates/${template}.js`, js);

94

});

95

```

96

97

### Compile Client With Dependencies Tracked

98

99

Compiles a template with full dependency tracking for build systems.

100

101

```javascript { .api }

102

/**

103

* Compile template with dependency tracking

104

* @param str - Pug template source code

105

* @param options - Compilation options

106

* @returns Object with body (JavaScript code) and dependencies array

107

*/

108

function compileClientWithDependenciesTracked(str, options);

109

```

110

111

**Usage Examples:**

112

113

```javascript

114

const pug = require('pug');

115

116

// Template with includes/extends

117

const result = pug.compileClientWithDependenciesTracked(`

118

extends layout.pug

119

120

block content

121

include components/header.pug

122

div.main-content

123

h1= title

124

p= content

125

`, {

126

filename: './views/page.pug',

127

basedir: './views'

128

});

129

130

console.log(result.body); // JavaScript template code

131

console.log(result.dependencies);

132

// ['./views/layout.pug', './views/components/header.pug']

133

134

// Use in build system for file watching

135

const watchFiles = [result.filename, ...result.dependencies];

136

watchFiles.forEach(file => {

137

fs.watchFile(file, () => {

138

console.log(`Template dependency ${file} changed, rebuilding...`);

139

// Rebuild template

140

});

141

});

142

```

143

144

### Client Compilation Options

145

146

Client compilation functions accept specialized options:

147

148

```javascript { .api }

149

interface ClientCompilationOptions extends CompilationOptions {

150

/** Name for the generated template function (default: 'template') */

151

name?: string;

152

/** Include runtime functions inline (default: false for compileClient) */

153

inlineRuntimeFunctions?: boolean;

154

/** Generate module.exports syntax for CommonJS (default: false) */

155

module?: boolean;

156

/** Enable template caching for compileFileClient */

157

cache?: boolean;

158

}

159

```

160

161

### Generated Template Usage

162

163

The generated client-side templates can be used in browsers:

164

165

```html

166

<!-- Include Pug runtime (if not inlined) -->

167

<script src="https://unpkg.com/pug-runtime@2.0.5/index.js"></script>

168

169

<!-- Include your compiled template -->

170

<script src="templates/user-card.js"></script>

171

172

<script>

173

// Use the compiled template

174

const html = userCardTemplate({

175

user: {

176

name: 'Alice Smith',

177

email: 'alice@example.com',

178

verified: true

179

}

180

});

181

182

document.getElementById('container').innerHTML = html;

183

</script>

184

```

185

186

### Module System Support

187

188

Generate templates compatible with different module systems:

189

190

```javascript

191

// CommonJS module

192

const clientJS = pug.compileClient('p Hello #{name}!', {

193

name: 'myTemplate',

194

module: true,

195

inlineRuntimeFunctions: false

196

});

197

// Generates: var pug = require("pug-runtime"); ... module.exports = myTemplate;

198

199

// Inline runtime (no external dependencies)

200

const clientJS2 = pug.compileClient('p Hello #{name}!', {

201

name: 'myTemplate',

202

inlineRuntimeFunctions: true

203

});

204

// Generates: function myTemplate(locals) { /* all runtime code included */ }

205

```

206

207

### Advanced Usage

208

209

**Template Bundling:**

210

211

```javascript

212

// Bundle multiple templates into one file

213

const templates = {

214

userCard: pug.compileClient(fs.readFileSync('./user-card.pug', 'utf8'), {

215

name: 'userCard',

216

inlineRuntimeFunctions: true

217

}),

218

productList: pug.compileClient(fs.readFileSync('./product-list.pug', 'utf8'), {

219

name: 'productList',

220

inlineRuntimeFunctions: true

221

})

222

};

223

224

const bundle = `

225

window.Templates = {

226

${templates.userCard},

227

${templates.productList}

228

};

229

`;

230

231

fs.writeFileSync('./dist/templates.js', bundle);

232

```

233

234

**Webpack Integration:**

235

236

```javascript

237

// webpack.config.js

238

const pug = require('pug');

239

240

module.exports = {

241

module: {

242

rules: [

243

{

244

test: /\.pug$/,

245

use: [

246

{

247

loader: 'apply-loader'

248

},

249

{

250

loader: 'pug-loader',

251

options: {

252

root: path.resolve(__dirname, 'src/templates')

253

}

254

}

255

]

256

}

257

]

258

}

259

};

260

261

// Usage in JavaScript

262

import template from './templates/user-profile.pug';

263

const html = template({ user: userData });

264

```

265

266

**Runtime Function Inlining:**

267

268

```javascript

269

// Without inlining - requires pug-runtime

270

const template1 = pug.compileClient('p #{name}', {

271

inlineRuntimeFunctions: false

272

});

273

// Needs: <script src="pug-runtime.js"></script>

274

275

// With inlining - standalone

276

const template2 = pug.compileClient('p #{name}', {

277

inlineRuntimeFunctions: true

278

});

279

// No external dependencies needed

280

```

281

282

### Build System Integration

283

284

Client compilation integrates well with build tools:

285

286

```javascript

287

// Gulp task

288

gulp.task('compile-templates', function() {

289

return gulp.src('./src/templates/**/*.pug')

290

.pipe(through2.obj(function(file, enc, callback) {

291

const compiled = pug.compileClient(file.contents.toString(), {

292

filename: file.path,

293

name: path.basename(file.path, '.pug') + 'Template'

294

});

295

296

file.contents = Buffer.from(compiled);

297

file.extname = '.js';

298

callback(null, file);

299

}))

300

.pipe(gulp.dest('./dist/templates/'));

301

});

302

303

// Rollup plugin

304

function pugPlugin() {

305

return {

306

name: 'pug',

307

transform(code, id) {

308

if (!id.endsWith('.pug')) return null;

309

310

const compiled = pug.compileClient(code, {

311

filename: id,

312

inlineRuntimeFunctions: true

313

});

314

315

return `export default ${compiled}`;

316

}

317

};

318

}

319

```

320

321

### Error Handling

322

323

Client compilation errors are similar to server-side compilation:

324

325

```javascript

326

try {

327

const clientJS = pug.compileClient('invalid syntax {{}}');

328

} catch (err) {

329

console.error('Client compilation failed:', err.message);

330

console.error('Line:', err.line);

331

console.error('Filename:', err.filename);

332

}

333

334

// File compilation errors

335

try {

336

const clientJS = pug.compileFileClient('./missing-template.pug');

337

} catch (err) {

338

console.error('File not found:', err.code);

339

}

340

```