0
# Language Support
1
2
Comprehensive programming language support with over 472 language definitions across highlight.js and Prism.js engines (193 for highlight.js, 279 for Prism.js). The library provides extensive coverage for both traditional and modern programming languages, markup languages, and configuration formats.
3
4
## Capabilities
5
6
### Supported Languages Access
7
8
Access to the complete list of supported languages for each engine.
9
10
```javascript { .api }
11
/**
12
* Array of supported language identifiers for each engine
13
*/
14
interface LanguageSupport {
15
/** Highlight.js supported languages (~190 languages) */
16
hljsLanguages: string[];
17
/** Prism.js supported languages (~280 languages) */
18
prismLanguages: string[];
19
}
20
21
// Access supported languages from components
22
const hljsLanguages: string[] = SyntaxHighlighter.supportedLanguages;
23
const prismLanguages: string[] = Prism.supportedLanguages;
24
```
25
26
**Usage Examples:**
27
28
```javascript
29
import SyntaxHighlighter from 'react-syntax-highlighter';
30
import { Prism } from 'react-syntax-highlighter';
31
32
// Check language support
33
const LanguageChecker = ({ language }) => {
34
const hljsSupported = SyntaxHighlighter.supportedLanguages.includes(language);
35
const prismSupported = Prism.supportedLanguages.includes(language);
36
37
return (
38
<div>
39
<p>Highlight.js supports {language}: {hljsSupported ? '✓' : '✗'}</p>
40
<p>Prism.js supports {language}: {prismSupported ? '✓' : '✗'}</p>
41
</div>
42
);
43
};
44
45
// List all supported languages
46
const LanguageList = () => {
47
return (
48
<div>
49
<h3>Highlight.js Languages ({SyntaxHighlighter.supportedLanguages.length})</h3>
50
<ul>
51
{SyntaxHighlighter.supportedLanguages.map(lang => (
52
<li key={lang}>{lang}</li>
53
))}
54
</ul>
55
56
<h3>Prism.js Languages ({Prism.supportedLanguages.length})</h3>
57
<ul>
58
{Prism.supportedLanguages.map(lang => (
59
<li key={lang}>{lang}</li>
60
))}
61
</ul>
62
</div>
63
);
64
};
65
```
66
67
### Language Import for Light Builds
68
69
Individual language imports for optimized bundle sizes in light builds.
70
71
```javascript { .api }
72
// Highlight.js language imports
73
import javascript from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript';
74
import python from 'react-syntax-highlighter/dist/esm/languages/hljs/python';
75
import java from 'react-syntax-highlighter/dist/esm/languages/hljs/java';
76
import cpp from 'react-syntax-highlighter/dist/esm/languages/hljs/cpp';
77
import csharp from 'react-syntax-highlighter/dist/esm/languages/hljs/csharp';
78
import go from 'react-syntax-highlighter/dist/esm/languages/hljs/go';
79
import rust from 'react-syntax-highlighter/dist/esm/languages/hljs/rust';
80
import typescript from 'react-syntax-highlighter/dist/esm/languages/hljs/typescript';
81
82
// Prism.js language imports
83
import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';
84
import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
85
import vue from 'react-syntax-highlighter/dist/esm/languages/prism/vue';
86
import svelte from 'react-syntax-highlighter/dist/esm/languages/prism/svelte';
87
import graphql from 'react-syntax-highlighter/dist/esm/languages/prism/graphql';
88
import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
89
import dockerfile from 'react-syntax-highlighter/dist/esm/languages/prism/docker';
90
```
91
92
**Language Registration Examples:**
93
94
```javascript
95
import { Light as SyntaxHighlighter } from 'react-syntax-highlighter';
96
import { PrismLight } from 'react-syntax-highlighter';
97
98
// Register highlight.js languages
99
import javascript from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript';
100
import python from 'react-syntax-highlighter/dist/esm/languages/hljs/python';
101
102
SyntaxHighlighter.registerLanguage('javascript', javascript);
103
SyntaxHighlighter.registerLanguage('python', python);
104
105
// Register Prism languages
106
import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';
107
import typescript from 'react-syntax-highlighter/dist/esm/languages/prism/typescript';
108
109
PrismLight.registerLanguage('jsx', jsx);
110
PrismLight.registerLanguage('typescript', typescript);
111
112
// Usage after registration
113
const MultiLanguageExample = () => {
114
const jsCode = `const greeting = (name) => \`Hello, \${name}!\`;`;
115
const pyCode = `def greeting(name): return f"Hello, {name}!"`;
116
const jsxCode = `const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;`;
117
118
return (
119
<div>
120
<SyntaxHighlighter language="javascript">{jsCode}</SyntaxHighlighter>
121
<SyntaxHighlighter language="python">{pyCode}</SyntaxHighlighter>
122
<PrismLight language="jsx">{jsxCode}</PrismLight>
123
</div>
124
);
125
};
126
```
127
128
### Popular Programming Languages
129
130
Coverage of widely-used programming languages with examples.
131
132
```javascript
133
const PopularLanguagesDemo = () => {
134
const languages = {
135
javascript: `// Modern JavaScript with ES6+
136
const users = [
137
{ name: 'Alice', age: 30 },
138
{ name: 'Bob', age: 25 }
139
];
140
141
const adults = users
142
.filter(user => user.age >= 18)
143
.map(user => ({ ...user, isAdult: true }));
144
145
const fetchUserData = async (userId) => {
146
try {
147
const response = await fetch(\`/api/users/\${userId}\`);
148
return await response.json();
149
} catch (error) {
150
console.error('Failed to fetch user:', error);
151
throw error;
152
}
153
};`,
154
155
python: `# Python with modern features
156
from typing import List, Dict, Optional
157
import asyncio
158
import aiohttp
159
160
class UserService:
161
def __init__(self, base_url: str):
162
self.base_url = base_url
163
164
async def fetch_user(self, user_id: int) -> Optional[Dict]:
165
async with aiohttp.ClientSession() as session:
166
async with session.get(f"{self.base_url}/users/{user_id}") as response:
167
if response.status == 200:
168
return await response.json()
169
return None
170
171
def process_users(self, users: List[Dict]) -> List[Dict]:
172
return [
173
{**user, 'full_name': f"{user['first_name']} {user['last_name']}"}
174
for user in users
175
if user.get('active', False)
176
]`,
177
178
java: `// Modern Java with records and pattern matching
179
import java.util.List;
180
import java.util.Optional;
181
import java.util.stream.Collectors;
182
183
public record User(String name, int age, boolean active) {}
184
185
public class UserProcessor {
186
private final List<User> users;
187
188
public UserProcessor(List<User> users) {
189
this.users = users;
190
}
191
192
public List<User> getActiveAdults() {
193
return users.stream()
194
.filter(User::active)
195
.filter(user -> user.age() >= 18)
196
.collect(Collectors.toList());
197
}
198
199
public Optional<User> findUserByName(String name) {
200
return users.stream()
201
.filter(user -> user.name().equals(name))
202
.findFirst();
203
}
204
}`,
205
206
rust: `// Rust with modern async and error handling
207
use std::collections::HashMap;
208
use serde::{Deserialize, Serialize};
209
use tokio;
210
211
#[derive(Debug, Serialize, Deserialize)]
212
struct User {
213
id: u64,
214
name: String,
215
email: String,
216
active: bool,
217
}
218
219
#[derive(Debug)]
220
enum UserError {
221
NotFound(u64),
222
NetworkError(String),
223
SerializationError,
224
}
225
226
struct UserService {
227
client: reqwest::Client,
228
base_url: String,
229
}
230
231
impl UserService {
232
fn new(base_url: String) -> Self {
233
Self {
234
client: reqwest::Client::new(),
235
base_url,
236
}
237
}
238
239
async fn fetch_user(&self, id: u64) -> Result<User, UserError> {
240
let url = format!("{}/users/{}", self.base_url, id);
241
242
let response = self.client
243
.get(&url)
244
.send()
245
.await
246
.map_err(|e| UserError::NetworkError(e.to_string()))?;
247
248
if response.status() == 404 {
249
return Err(UserError::NotFound(id));
250
}
251
252
response
253
.json::<User>()
254
.await
255
.map_err(|_| UserError::SerializationError)
256
}
257
}`
258
};
259
260
return (
261
<div>
262
{Object.entries(languages).map(([lang, code]) => (
263
<div key={lang} style={{ marginBottom: '2rem' }}>
264
<h3>{lang.toUpperCase()}</h3>
265
<SyntaxHighlighter language={lang} style={github}>
266
{code}
267
</SyntaxHighlighter>
268
</div>
269
))}
270
</div>
271
);
272
};
273
```
274
275
### Web Technologies and Markup
276
277
Specialized support for web development languages and markup formats.
278
279
```javascript
280
const WebTechnologiesDemo = () => {
281
const webLanguages = {
282
jsx: `// React JSX with hooks and modern patterns
283
import React, { useState, useEffect, useCallback } from 'react';
284
import { useQuery, useMutation } from 'react-query';
285
286
interface User {
287
id: number;
288
name: string;
289
email: string;
290
}
291
292
const UserProfile: React.FC<{ userId: number }> = ({ userId }) => {
293
const [isEditing, setIsEditing] = useState(false);
294
295
const { data: user, isLoading } = useQuery(
296
['user', userId],
297
() => fetchUser(userId)
298
);
299
300
const updateMutation = useMutation(updateUser, {
301
onSuccess: () => {
302
setIsEditing(false);
303
queryClient.invalidateQueries(['user', userId]);
304
}
305
});
306
307
const handleSubmit = useCallback((formData: User) => {
308
updateMutation.mutate(formData);
309
}, [updateMutation]);
310
311
if (isLoading) return <div>Loading...</div>;
312
313
return (
314
<div className="user-profile">
315
<h2>{user?.name}</h2>
316
{isEditing ? (
317
<UserForm
318
user={user}
319
onSubmit={handleSubmit}
320
onCancel={() => setIsEditing(false)}
321
/>
322
) : (
323
<UserDisplay
324
user={user}
325
onEdit={() => setIsEditing(true)}
326
/>
327
)}
328
</div>
329
);
330
};`,
331
332
scss: `// Modern SCSS with CSS Grid and Flexbox
333
@import 'variables';
334
@import 'mixins';
335
336
// CSS Custom Properties
337
:root {
338
--primary-color: #{$primary-blue};
339
--secondary-color: #{$secondary-green};
340
--font-size-base: 16px;
341
--spacing-unit: 8px;
342
--border-radius: 8px;
343
--transition-duration: 0.3s;
344
}
345
346
// Mixins
347
@mixin flex-center {
348
display: flex;
349
align-items: center;
350
justify-content: center;
351
}
352
353
@mixin responsive-grid($min-width: 300px, $gap: 2rem) {
354
display: grid;
355
grid-template-columns: repeat(auto-fit, minmax($min-width, 1fr));
356
gap: $gap;
357
}
358
359
// Component styles
360
.user-dashboard {
361
@include responsive-grid(350px, 1.5rem);
362
padding: calc(var(--spacing-unit) * 3);
363
364
&__header {
365
grid-column: 1 / -1;
366
@include flex-center;
367
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
368
border-radius: var(--border-radius);
369
color: white;
370
padding: calc(var(--spacing-unit) * 2);
371
372
h1 {
373
margin: 0;
374
font-size: calc(var(--font-size-base) * 1.75);
375
}
376
}
377
378
&__card {
379
background: white;
380
border-radius: var(--border-radius);
381
padding: calc(var(--spacing-unit) * 2);
382
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
383
transition: transform var(--transition-duration) ease;
384
385
&:hover {
386
transform: translateY(-2px);
387
}
388
389
@media (max-width: 768px) {
390
padding: var(--spacing-unit);
391
}
392
}
393
}`,
394
395
html: `<!DOCTYPE html>
396
<html lang="en">
397
<head>
398
<meta charset="UTF-8">
399
<meta name="viewport" content="width=device-width, initial-scale=1.0">
400
<title>Modern Web App</title>
401
<link rel="preconnect" href="https://fonts.googleapis.com">
402
<link rel="stylesheet" href="styles.css">
403
<script type="module" src="app.js" defer></script>
404
</head>
405
<body>
406
<header class="app-header">
407
<nav class="navbar" role="navigation" aria-label="main navigation">
408
<div class="navbar-brand">
409
<img src="logo.svg" alt="Company Logo" width="120" height="40">
410
</div>
411
<ul class="navbar-menu" id="navbar-menu">
412
<li><a href="#home" class="navbar-item">Home</a></li>
413
<li><a href="#about" class="navbar-item">About</a></li>
414
<li><a href="#services" class="navbar-item">Services</a></li>
415
<li><a href="#contact" class="navbar-item">Contact</a></li>
416
</ul>
417
<button class="navbar-toggle" aria-controls="navbar-menu" aria-expanded="false">
418
<span class="sr-only">Toggle navigation</span>
419
<span class="hamburger"></span>
420
</button>
421
</nav>
422
</header>
423
424
<main class="main-content">
425
<section class="hero" aria-labelledby="hero-title">
426
<div class="container">
427
<h1 id="hero-title">Welcome to Our Platform</h1>
428
<p class="hero-subtitle">Build amazing things with our tools</p>
429
<div class="hero-actions">
430
<button class="btn btn-primary">Get Started</button>
431
<button class="btn btn-secondary">Learn More</button>
432
</div>
433
</div>
434
</section>
435
436
<section class="features" aria-labelledby="features-title">
437
<div class="container">
438
<h2 id="features-title">Features</h2>
439
<div class="features-grid">
440
<article class="feature-card">
441
<svg class="feature-icon" aria-hidden="true">
442
<use href="#icon-fast"></use>
443
</svg>
444
<h3>Lightning Fast</h3>
445
<p>Optimized for performance with modern web standards.</p>
446
</article>
447
</div>
448
</div>
449
</section>
450
</main>
451
452
<footer class="app-footer">
453
<div class="container">
454
<p>© 2023 Company Name. All rights reserved.</p>
455
</div>
456
</footer>
457
</body>
458
</html>`
459
};
460
461
return (
462
<div>
463
{Object.entries(webLanguages).map(([lang, code]) => (
464
<div key={lang} style={{ marginBottom: '2rem' }}>
465
<h3>{lang.toUpperCase()}</h3>
466
<Prism language={lang} style={tomorrow}>
467
{code}
468
</Prism>
469
</div>
470
))}
471
</div>
472
);
473
};
474
```
475
476
### Configuration and Data Formats
477
478
Support for various configuration files and data interchange formats.
479
480
```javascript
481
const ConfigurationFormatsDemo = () => {
482
const configFormats = {
483
yaml: `# Kubernetes Deployment Configuration
484
apiVersion: apps/v1
485
kind: Deployment
486
metadata:
487
name: webapp-deployment
488
labels:
489
app: webapp
490
spec:
491
replicas: 3
492
selector:
493
matchLabels:
494
app: webapp
495
template:
496
metadata:
497
labels:
498
app: webapp
499
spec:
500
containers:
501
- name: webapp
502
image: nginx:1.21-alpine
503
ports:
504
- containerPort: 80
505
env:
506
- name: NODE_ENV
507
value: "production"
508
- name: DATABASE_URL
509
valueFrom:
510
secretKeyRef:
511
name: database-secret
512
key: url
513
resources:
514
limits:
515
memory: "512Mi"
516
cpu: "500m"
517
requests:
518
memory: "256Mi"
519
cpu: "250m"
520
readinessProbe:
521
httpGet:
522
path: /health
523
port: 80
524
initialDelaySeconds: 10
525
periodSeconds: 5`,
526
527
json: `{
528
"name": "my-web-app",
529
"version": "2.1.0",
530
"description": "A modern web application",
531
"main": "dist/index.js",
532
"scripts": {
533
"dev": "vite",
534
"build": "tsc && vite build",
535
"preview": "vite preview",
536
"test": "vitest",
537
"test:coverage": "vitest --coverage",
538
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
539
"type-check": "tsc --noEmit"
540
},
541
"dependencies": {
542
"react": "^18.2.0",
543
"react-dom": "^18.2.0",
544
"react-router-dom": "^6.8.0",
545
"@tanstack/react-query": "^4.24.0",
546
"axios": "^1.3.0",
547
"zustand": "^4.3.0"
548
},
549
"devDependencies": {
550
"@types/react": "^18.0.27",
551
"@types/react-dom": "^18.0.10",
552
"@vitejs/plugin-react": "^3.1.0",
553
"vite": "^4.1.0",
554
"typescript": "^4.9.0",
555
"vitest": "^0.28.0",
556
"@testing-library/react": "^13.4.0"
557
},
558
"engines": {
559
"node": ">=16.0.0",
560
"npm": ">=8.0.0"
561
}
562
}`,
563
564
dockerfile: `# Multi-stage Docker build for Node.js application
565
FROM node:18-alpine AS builder
566
567
# Set working directory
568
WORKDIR /app
569
570
# Copy package files
571
COPY package.json package-lock.json ./
572
573
# Install dependencies
574
RUN npm ci --only=production
575
576
# Copy source code
577
COPY . .
578
579
# Build application
580
RUN npm run build
581
582
# Production stage
583
FROM node:18-alpine AS production
584
585
# Create non-root user
586
RUN addgroup -g 1001 -S nodejs
587
RUN adduser -S nextjs -u 1001
588
589
# Set working directory
590
WORKDIR /app
591
592
# Copy built application from builder stage
593
COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist
594
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
595
COPY --from=builder --chown=nextjs:nodejs /app/package.json ./package.json
596
597
# Switch to non-root user
598
USER nextjs
599
600
# Expose port
601
EXPOSE 3000
602
603
# Health check
604
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
605
CMD curl -f http://localhost:3000/health || exit 1
606
607
# Start application
608
CMD ["npm", "start"]`,
609
610
toml: `# Rust Cargo.toml configuration
611
[package]
612
name = "web-server"
613
version = "0.3.0"
614
edition = "2021"
615
authors = ["Developer <dev@example.com>"]
616
description = "A high-performance web server built with Rust"
617
license = "MIT OR Apache-2.0"
618
repository = "https://github.com/user/web-server"
619
readme = "README.md"
620
keywords = ["web", "server", "async", "performance"]
621
categories = ["web-programming::http-server"]
622
623
[dependencies]
624
tokio = { version = "1.25", features = ["full"] }
625
axum = "0.6"
626
serde = { version = "1.0", features = ["derive"] }
627
serde_json = "1.0"
628
sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono"] }
629
uuid = { version = "1.3", features = ["v4", "serde"] }
630
chrono = { version = "0.4", features = ["serde"] }
631
tracing = "0.1"
632
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
633
clap = { version = "4.1", features = ["derive"] }
634
635
[dev-dependencies]
636
tokio-test = "0.4"
637
axum-test = "11.0"
638
639
[profile.release]
640
lto = true
641
codegen-units = 1
642
panic = "abort"`
643
};
644
645
return (
646
<div>
647
{Object.entries(configFormats).map(([lang, code]) => (
648
<div key={lang} style={{ marginBottom: '2rem' }}>
649
<h3>{lang.toUpperCase()}</h3>
650
<Prism language={lang} style={tomorrow}>
651
{code}
652
</Prism>
653
</div>
654
))}
655
</div>
656
);
657
};
658
```
659
660
### Language Detection and Fallbacks
661
662
Handling unknown languages and providing fallback options.
663
664
```javascript { .api }
665
/**
666
* Language detection and fallback strategies
667
*/
668
interface LanguageDetectionOptions {
669
/** Language identifier or 'text' for plain text */
670
language?: string;
671
/** Fallback to plain text for unsupported languages */
672
fallbackToText?: boolean;
673
/** Custom language detection function */
674
detectLanguage?: (code: string) => string;
675
}
676
```
677
678
**Language Detection Examples:**
679
680
```javascript
681
const SmartLanguageHighlighter = ({ code, language, ...props }) => {
682
const [detectedLanguage, setDetectedLanguage] = useState(language);
683
684
useEffect(() => {
685
if (!language || language === 'auto') {
686
// Simple heuristic language detection
687
const detectLanguage = (code) => {
688
if (code.includes('function') && code.includes('{')) return 'javascript';
689
if (code.includes('def ') && code.includes(':')) return 'python';
690
if (code.includes('class ') && code.includes('public')) return 'java';
691
if (code.includes('<') && code.includes('>')) return 'html';
692
if (code.includes('SELECT') || code.includes('FROM')) return 'sql';
693
return 'text';
694
};
695
696
setDetectedLanguage(detectLanguage(code));
697
}
698
}, [code, language]);
699
700
// Check if language is supported
701
const isSupported = SyntaxHighlighter.supportedLanguages.includes(detectedLanguage);
702
const finalLanguage = isSupported ? detectedLanguage : 'text';
703
704
return (
705
<div>
706
{!isSupported && detectedLanguage !== 'text' && (
707
<div style={{ color: 'orange', fontSize: '12px', marginBottom: '4px' }}>
708
Language '{detectedLanguage}' not supported, showing as plain text
709
</div>
710
)}
711
<SyntaxHighlighter
712
language={finalLanguage}
713
{...props}
714
>
715
{code}
716
</SyntaxHighlighter>
717
</div>
718
);
719
};
720
721
// Usage with automatic detection
722
const AutoDetectExample = () => {
723
const codeSnippets = [
724
'console.log("Hello, World!");',
725
'print("Hello, World!")',
726
'System.out.println("Hello, World!");',
727
'<h1>Hello, World!</h1>',
728
'SELECT * FROM users WHERE active = true;'
729
];
730
731
return (
732
<div>
733
{codeSnippets.map((code, index) => (
734
<SmartLanguageHighlighter
735
key={index}
736
code={code}
737
language="auto"
738
style={github}
739
/>
740
))}
741
</div>
742
);
743
};
744
```
745
746
### Custom Language Extensions
747
748
Adding support for domain-specific languages or extending existing language definitions.
749
750
```javascript
751
const CustomLanguageExample = () => {
752
// Register a custom language
753
useEffect(() => {
754
// Define custom SQL dialect
755
const customSQL = {
756
...sqlLanguage,
757
keywords: [
758
...sqlLanguage.keywords,
759
'UPSERT', 'MERGE', 'WINDOW', 'PARTITION'
760
],
761
functions: [
762
...sqlLanguage.functions,
763
'LAG', 'LEAD', 'ROW_NUMBER', 'RANK', 'DENSE_RANK'
764
]
765
};
766
767
SyntaxHighlighter.registerLanguage('custom-sql', customSQL);
768
}, []);
769
770
const customSQLCode = `-- Advanced SQL with window functions
771
WITH monthly_sales AS (
772
SELECT
773
DATE_TRUNC('month', sale_date) as month,
774
SUM(amount) as total_sales,
775
LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', sale_date)) as prev_month_sales
776
FROM sales
777
WHERE sale_date >= '2023-01-01'
778
GROUP BY DATE_TRUNC('month', sale_date)
779
),
780
growth_analysis AS (
781
SELECT
782
month,
783
total_sales,
784
prev_month_sales,
785
CASE
786
WHEN prev_month_sales IS NOT NULL
787
THEN ((total_sales - prev_month_sales) / prev_month_sales) * 100
788
ELSE NULL
789
END as growth_percentage,
790
ROW_NUMBER() OVER (ORDER BY total_sales DESC) as sales_rank
791
FROM monthly_sales
792
)
793
SELECT
794
month,
795
total_sales,
796
growth_percentage,
797
sales_rank,
798
CASE
799
WHEN sales_rank <= 3 THEN 'Top Performer'
800
WHEN growth_percentage > 10 THEN 'High Growth'
801
ELSE 'Standard'
802
END as performance_category
803
FROM growth_analysis
804
ORDER BY month;`;
805
806
return (
807
<SyntaxHighlighter language="custom-sql" style={github}>
808
{customSQLCode}
809
</SyntaxHighlighter>
810
);
811
};
812
```
813
814
## Best Practices
815
816
### Language Selection Strategy
817
818
```javascript
819
const LanguageStrategy = {
820
// Use Prism for modern web development
821
webDevelopment: ['jsx', 'tsx', 'vue', 'svelte', 'graphql', 'mdx'],
822
823
// Use highlight.js for general programming
824
generalProgramming: ['python', 'java', 'cpp', 'csharp', 'go', 'rust'],
825
826
// Both engines support these well
827
common: ['javascript', 'typescript', 'css', 'html', 'json', 'yaml', 'sql'],
828
829
// Specialized use cases
830
specialized: {
831
'data-science': ['python', 'r', 'julia', 'matlab'],
832
'systems': ['c', 'cpp', 'rust', 'assembly'],
833
'web': ['html', 'css', 'scss', 'jsx', 'vue'],
834
'config': ['yaml', 'toml', 'ini', 'dockerfile']
835
}
836
};
837
```
838
839
### Performance Optimization
840
841
```javascript
842
// Lazy load languages for better performance
843
const LazyLanguageLoader = ({ language, children, ...props }) => {
844
const [isLoaded, setIsLoaded] = useState(false);
845
846
useEffect(() => {
847
const loadLanguage = async () => {
848
try {
849
const lang = await import(`react-syntax-highlighter/dist/esm/languages/hljs/${language}`);
850
SyntaxHighlighter.registerLanguage(language, lang.default);
851
setIsLoaded(true);
852
} catch (error) {
853
console.warn(`Failed to load language: ${language}`);
854
setIsLoaded(true); // Show as plain text
855
}
856
};
857
858
if (!SyntaxHighlighter.supportedLanguages.includes(language)) {
859
loadLanguage();
860
} else {
861
setIsLoaded(true);
862
}
863
}, [language]);
864
865
if (!isLoaded) {
866
return <pre style={{ opacity: 0.6 }}>{children}</pre>;
867
}
868
869
return (
870
<SyntaxHighlighter language={language} {...props}>
871
{children}
872
</SyntaxHighlighter>
873
);
874
};
875
```