or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-builds.mdindex.mdlanguage-support.mdlight-builds.mdprism-integration.mdstandard-highlighter.mdstyling-themes.md

prism-integration.mddocs/

0

# Prism.js Integration

1

2

Enhanced syntax highlighting using Prism.js through the refractor AST parser. Prism.js offers extended language support including modern web technologies like JSX, TSX, and improved highlighting for various programming languages.

3

4

## Capabilities

5

6

### Prism (Full Build)

7

8

Full Prism.js build with comprehensive language support and default Prism styling.

9

10

```javascript { .api }

11

/**

12

* React syntax highlighter component using Prism.js (refractor)

13

*/

14

const Prism: SyntaxHighlighterComponent & {

15

/** Array of supported language identifiers */

16

supportedLanguages: string[];

17

};

18

19

type SyntaxHighlighterComponent = React.ComponentType<SyntaxHighlighterProps>;

20

```

21

22

**Usage Examples:**

23

24

```javascript

25

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

26

import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';

27

28

// JSX highlighting (Prism.js specialty)

29

const JSXExample = () => {

30

const jsxCode = `import React, { useState } from 'react';

31

32

const Counter = ({ initialCount = 0 }) => {

33

const [count, setCount] = useState(initialCount);

34

35

return (

36

<div className="counter">

37

<p>Count: {count}</p>

38

<button onClick={() => setCount(count + 1)}>

39

Increment

40

</button>

41

<button onClick={() => setCount(count - 1)}>

42

Decrement

43

</button>

44

</div>

45

);

46

};

47

48

export default Counter;`;

49

50

return (

51

<SyntaxHighlighter language="jsx" style={dark}>

52

{jsxCode}

53

</SyntaxHighlighter>

54

);

55

};

56

57

// TypeScript highlighting

58

const TypeScriptExample = () => {

59

const tsCode = `interface User {

60

id: number;

61

name: string;

62

email: string;

63

profile?: UserProfile;

64

}

65

66

interface UserProfile {

67

avatar: string;

68

bio: string;

69

location?: string;

70

}

71

72

class UserService {

73

private users: Map<number, User> = new Map();

74

75

async createUser(userData: Omit<User, 'id'>): Promise<User> {

76

const id = Math.max(...this.users.keys()) + 1;

77

const user: User = { id, ...userData };

78

79

this.users.set(id, user);

80

return user;

81

}

82

83

getUserById(id: number): User | undefined {

84

return this.users.get(id);

85

}

86

}`;

87

88

return (

89

<SyntaxHighlighter language="typescript" style={dark}>

90

{tsCode}

91

</SyntaxHighlighter>

92

);

93

};

94

```

95

96

### PrismLight (Core Build)

97

98

Light Prism.js build requiring manual language registration.

99

100

```javascript { .api }

101

/**

102

* Light Prism.js syntax highlighter requiring manual language registration

103

*/

104

const PrismLight: SyntaxHighlighterComponent & {

105

/** Register a Prism language definition */

106

registerLanguage: (name: string, language: any) => void;

107

/** Create language aliases for existing registered languages */

108

alias: (name: string, aliases: string | string[]) => void;

109

};

110

```

111

112

**Usage Examples:**

113

114

```javascript

115

import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';

116

import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';

117

import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';

118

import prism from 'react-syntax-highlighter/dist/esm/styles/prism/prism';

119

120

// Register required languages

121

SyntaxHighlighter.registerLanguage('jsx', jsx);

122

SyntaxHighlighter.registerLanguage('typescript', typescript);

123

124

// Create language aliases

125

SyntaxHighlighter.alias('typescript', ['ts']);

126

SyntaxHighlighter.alias('jsx', ['react']);

127

128

const PrismLightExample = () => {

129

return (

130

<SyntaxHighlighter language="jsx" style={prism}>

131

{jsxCode}

132

</SyntaxHighlighter>

133

);

134

};

135

```

136

137

### Advanced Language Support

138

139

Prism.js provides superior support for modern web technologies and markup languages.

140

141

```javascript

142

// Vue.js Single File Components

143

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

144

import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';

145

146

const VueExample = () => {

147

const vueCode = `<template>

148

<div class="user-profile">

149

<h2>{{ user.name }}</h2>

150

<img :src="user.avatar" :alt="user.name" />

151

<p v-if="user.bio">{{ user.bio }}</p>

152

<button @click="followUser">Follow</button>

153

</div>

154

</template>

155

156

<script>

157

export default {

158

name: 'UserProfile',

159

props: {

160

user: {

161

type: Object,

162

required: true

163

}

164

},

165

methods: {

166

followUser() {

167

this.$emit('follow', this.user.id);

168

}

169

}

170

}

171

</script>

172

173

<style scoped>

174

.user-profile {

175

border: 1px solid #ccc;

176

border-radius: 8px;

177

padding: 16px;

178

}

179

</style>`;

180

181

return (

182

<SyntaxHighlighter language="vue" style={tomorrow}>

183

{vueCode}

184

</SyntaxHighlighter>

185

);

186

};

187

188

// GraphQL Schema

189

const GraphQLExample = () => {

190

const graphqlCode = `type User {

191

id: ID!

192

name: String!

193

email: String!

194

posts: [Post!]!

195

createdAt: DateTime!

196

}

197

198

type Post {

199

id: ID!

200

title: String!

201

content: String!

202

author: User!

203

comments: [Comment!]!

204

publishedAt: DateTime

205

}

206

207

type Query {

208

users(first: Int, after: String): UserConnection!

209

user(id: ID!): User

210

posts(authorId: ID, published: Boolean): [Post!]!

211

}

212

213

type Mutation {

214

createUser(input: CreateUserInput!): User!

215

updateUser(id: ID!, input: UpdateUserInput!): User!

216

deleteUser(id: ID!): Boolean!

217

}`;

218

219

return (

220

<SyntaxHighlighter language="graphql" style={tomorrow}>

221

{graphqlCode}

222

</SyntaxHighlighter>

223

);

224

};

225

```

226

227

### Modern Web Framework Support

228

229

Enhanced support for popular web frameworks and their specific syntax.

230

231

```javascript

232

// Svelte Components

233

const SvelteExample = () => {

234

const svelteCode = `<script>

235

import { onMount } from 'svelte';

236

237

let count = 0;

238

let doubled;

239

240

$: doubled = count * 2;

241

242

onMount(() => {

243

console.log('Component mounted');

244

});

245

246

function increment() {

247

count += 1;

248

}

249

</script>

250

251

<main>

252

<h1>Count: {count}</h1>

253

<p>Doubled: {doubled}</p>

254

<button on:click={increment}>+</button>

255

</main>

256

257

<style>

258

main {

259

text-align: center;

260

padding: 1em;

261

}

262

</style>`;

263

264

return (

265

<SyntaxHighlighter language="svelte" style={tomorrow}>

266

{svelteCode}

267

</SyntaxHighlighter>

268

);

269

};

270

271

// MDX (Markdown + JSX)

272

const MDXExample = () => {

273

const mdxCode = `# My Blog Post

274

275

This is a regular markdown paragraph.

276

277

import { Chart } from './components/Chart';

278

import { DataTable } from './components/DataTable';

279

280

Here's an interactive chart embedded in markdown:

281

282

<Chart

283

data={salesData}

284

type="line"

285

title="Monthly Sales"

286

/>

287

288

## Code Examples

289

290

Here's some JavaScript:

291

292

\`\`\`javascript

293

const greeting = (name) => {

294

return \`Hello, \${name}!\`;

295

};

296

\`\`\`

297

298

And here's a data table:

299

300

<DataTable

301

columns={['Name', 'Age', 'City']}

302

data={userData}

303

sortable

304

/>

305

306

## Conclusion

307

308

This demonstrates the power of combining Markdown with React components.`;

309

310

return (

311

<SyntaxHighlighter language="mdx" style={tomorrow}>

312

{mdxCode}

313

</SyntaxHighlighter>

314

);

315

};

316

```

317

318

### Language-Specific Features

319

320

Prism.js provides better tokenization for specific language features.

321

322

```javascript

323

// CSS with Advanced Features

324

const CSSExample = () => {

325

const cssCode = `/* CSS Custom Properties and Grid */

326

:root {

327

--primary-color: #3498db;

328

--secondary-color: #2ecc71;

329

--font-size-base: 16px;

330

--border-radius: 8px;

331

}

332

333

.container {

334

display: grid;

335

grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));

336

grid-gap: 2rem;

337

padding: 2rem;

338

background: linear-gradient(

339

135deg,

340

var(--primary-color) 0%,

341

var(--secondary-color) 100%

342

);

343

}

344

345

.card {

346

background: white;

347

border-radius: var(--border-radius);

348

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

349

padding: 1.5rem;

350

transition: transform 0.2s ease-in-out;

351

}

352

353

.card:hover {

354

transform: translateY(-2px);

355

}

356

357

@media (max-width: 768px) {

358

.container {

359

grid-template-columns: 1fr;

360

padding: 1rem;

361

}

362

}`;

363

364

return (

365

<SyntaxHighlighter language="css" style={tomorrow}>

366

{cssCode}

367

</SyntaxHighlighter>

368

);

369

};

370

371

// Rust with Advanced Features

372

const RustExample = () => {

373

const rustCode = `use std::collections::HashMap;

374

use serde::{Deserialize, Serialize};

375

376

#[derive(Debug, Serialize, Deserialize)]

377

struct User {

378

id: u64,

379

name: String,

380

email: String,

381

age: Option<u8>,

382

}

383

384

#[derive(Debug)]

385

enum DatabaseError {

386

ConnectionFailed,

387

QueryFailed(String),

388

UserNotFound(u64),

389

}

390

391

impl std::fmt::Display for DatabaseError {

392

fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

393

match self {

394

DatabaseError::ConnectionFailed => write!(f, "Database connection failed"),

395

DatabaseError::QueryFailed(query) => write!(f, "Query failed: {}", query),

396

DatabaseError::UserNotFound(id) => write!(f, "User with id {} not found", id),

397

}

398

}

399

}

400

401

struct UserRepository {

402

users: HashMap<u64, User>,

403

}

404

405

impl UserRepository {

406

fn new() -> Self {

407

Self {

408

users: HashMap::new(),

409

}

410

}

411

412

fn create_user(&mut self, user: User) -> Result<u64, DatabaseError> {

413

let id = user.id;

414

self.users.insert(id, user);

415

Ok(id)

416

}

417

418

fn get_user(&self, id: u64) -> Result<&User, DatabaseError> {

419

self.users.get(&id).ok_or(DatabaseError::UserNotFound(id))

420

}

421

}`;

422

423

return (

424

<SyntaxHighlighter language="rust" style={tomorrow}>

425

{rustCode}

426

</SyntaxHighlighter>

427

);

428

};

429

```

430

431

### Prism vs Highlight.js Comparison

432

433

Understanding when to choose Prism.js over highlight.js.

434

435

```javascript

436

// Prism.js advantages:

437

// ✓ Better JSX/TSX support

438

// ✓ More modern web framework support (Vue, Svelte, etc.)

439

// ✓ Better CSS highlighting with modern features

440

// ✓ Enhanced markup language support (MDX, etc.)

441

// ✓ More granular tokenization

442

// ✓ Better plugin ecosystem

443

444

// Highlight.js advantages:

445

// ✓ Auto-detection of languages

446

// ✓ Smaller core size

447

// ✓ More language coverage overall

448

// ✓ Better performance for large code blocks

449

450

// Migration from highlight.js to Prism

451

// Before (highlight.js)

452

import SyntaxHighlighter from 'react-syntax-highlighter';

453

import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';

454

455

// After (Prism.js)

456

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

457

import { prism } from 'react-syntax-highlighter/dist/esm/styles/prism';

458

459

// Component usage remains the same

460

<SyntaxHighlighter language="jsx" style={prism}>

461

{code}

462

</SyntaxHighlighter>

463

```

464

465

### Custom Language Extensions

466

467

Adding custom language support to Prism.js builds.

468

469

```javascript

470

// Example: Adding custom templating language

471

import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';

472

473

// Define custom language grammar

474

const customTemplate = {

475

'template-tag': {

476

pattern: /\{\{[\s\S]*?\}\}/,

477

inside: {

478

'delimiter': {

479

pattern: /^\{\{|\}\}$/,

480

alias: 'punctuation'

481

},

482

'variable': /\b\w+\b/

483

}

484

},

485

'string': /"(?:[^"\\]|\\.)*"/,

486

'number': /\b\d+(?:\.\d+)?\b/,

487

'operator': /[=<>!]=?|[&|]{2}|\+\+?|--?/,

488

'punctuation': /[{}[\];(),.:]/

489

};

490

491

// Register the custom language

492

SyntaxHighlighter.registerLanguage('custom-template', customTemplate);

493

494

// Usage

495

const CustomTemplateExample = () => {

496

const templateCode = `<!DOCTYPE html>

497

<html>

498

<head>

499

<title>{{title}}</title>

500

</head>

501

<body>

502

<h1>Welcome, {{user.name}}!</h1>

503

{{#if user.isAdmin}}

504

<div class="admin-panel">

505

<a href="/admin">Admin Dashboard</a>

506

</div>

507

{{/if}}

508

509

<ul>

510

{{#each posts}}

511

<li>

512

<h2>{{title}}</h2>

513

<p>{{excerpt}}</p>

514

<small>By {{author}} on {{date}}</small>

515

</li>

516

{{/each}}

517

</ul>

518

</body>

519

</html>`;

520

521

return (

522

<SyntaxHighlighter language="custom-template" style={prism}>

523

{templateCode}

524

</SyntaxHighlighter>

525

);

526

};

527

```

528

529

## Best Practices

530

531

### Language Selection Strategy

532

533

```javascript

534

// Choose Prism.js for:

535

const modernWebProjects = {

536

frameworks: ['React', 'Vue', 'Svelte', 'Angular'],

537

languages: ['JSX', 'TSX', 'Vue SFC', 'Svelte'],

538

features: ['Modern CSS', 'GraphQL', 'MDX', 'Template literals']

539

};

540

541

// Choose highlight.js for:

542

const traditionalProjects = {

543

features: ['Auto-detection', 'Large code blocks', 'Performance-critical'],

544

languages: ['General programming', 'Server-side languages', 'Legacy syntax']

545

};

546

547

// Hybrid approach: Use both based on content type

548

const LanguageSelector = ({ language, children }) => {

549

const prismLanguages = ['jsx', 'tsx', 'vue', 'svelte', 'graphql', 'mdx'];

550

const usePrism = prismLanguages.includes(language);

551

552

if (usePrism) {

553

return (

554

<PrismSyntaxHighlighter language={language} style={prismStyle}>

555

{children}

556

</PrismSyntaxHighlighter>

557

);

558

}

559

560

return (

561

<HljsSyntaxHighlighter language={language} style={hljsStyle}>

562

{children}

563

</HljsSyntaxHighlighter>

564

);

565

};

566

```