CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-syntax-highlighter

React component library for syntax highlighting with highlight.js and Prism.js support.

Pending
Overview
Eval results
Files

language-support.mddocs/

Language Support

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.

Capabilities

Supported Languages Access

Access to the complete list of supported languages for each engine.

/**
 * Array of supported language identifiers for each engine
 */
interface LanguageSupport {
  /** Highlight.js supported languages (~190 languages) */
  hljsLanguages: string[];
  /** Prism.js supported languages (~280 languages) */
  prismLanguages: string[];
}

// Access supported languages from components
const hljsLanguages: string[] = SyntaxHighlighter.supportedLanguages;
const prismLanguages: string[] = Prism.supportedLanguages;

Usage Examples:

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

// Check language support
const LanguageChecker = ({ language }) => {
  const hljsSupported = SyntaxHighlighter.supportedLanguages.includes(language);
  const prismSupported = Prism.supportedLanguages.includes(language);

  return (
    <div>
      <p>Highlight.js supports {language}: {hljsSupported ? '✓' : '✗'}</p>
      <p>Prism.js supports {language}: {prismSupported ? '✓' : '✗'}</p>
    </div>
  );
};

// List all supported languages
const LanguageList = () => {
  return (
    <div>
      <h3>Highlight.js Languages ({SyntaxHighlighter.supportedLanguages.length})</h3>
      <ul>
        {SyntaxHighlighter.supportedLanguages.map(lang => (
          <li key={lang}>{lang}</li>
        ))}
      </ul>
      
      <h3>Prism.js Languages ({Prism.supportedLanguages.length})</h3>
      <ul>
        {Prism.supportedLanguages.map(lang => (
          <li key={lang}>{lang}</li>
        ))}
      </ul>
    </div>
  );
};

Language Import for Light Builds

Individual language imports for optimized bundle sizes in light builds.

// Highlight.js language imports
import javascript from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript';
import python from 'react-syntax-highlighter/dist/esm/languages/hljs/python';
import java from 'react-syntax-highlighter/dist/esm/languages/hljs/java';
import cpp from 'react-syntax-highlighter/dist/esm/languages/hljs/cpp';
import csharp from 'react-syntax-highlighter/dist/esm/languages/hljs/csharp';
import go from 'react-syntax-highlighter/dist/esm/languages/hljs/go';
import rust from 'react-syntax-highlighter/dist/esm/languages/hljs/rust';
import typescript from 'react-syntax-highlighter/dist/esm/languages/hljs/typescript';

// Prism.js language imports
import jsx from 'react-syntax-highlighter/dist/esm/languages/prism/jsx';
import tsx from 'react-syntax-highlighter/dist/esm/languages/prism/tsx';
import vue from 'react-syntax-highlighter/dist/esm/languages/prism/vue';
import svelte from 'react-syntax-highlighter/dist/esm/languages/prism/svelte';
import graphql from 'react-syntax-highlighter/dist/esm/languages/prism/graphql';
import yaml from 'react-syntax-highlighter/dist/esm/languages/prism/yaml';
import dockerfile from 'react-syntax-highlighter/dist/esm/languages/prism/docker';

Language Registration Examples:

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

// Register highlight.js languages
import javascript from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript';
import python from 'react-syntax-highlighter/dist/esm/languages/hljs/python';

SyntaxHighlighter.registerLanguage('javascript', javascript);
SyntaxHighlighter.registerLanguage('python', python);

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

PrismLight.registerLanguage('jsx', jsx);
PrismLight.registerLanguage('typescript', typescript);

// Usage after registration
const MultiLanguageExample = () => {
  const jsCode = `const greeting = (name) => \`Hello, \${name}!\`;`;
  const pyCode = `def greeting(name): return f"Hello, {name}!"`;
  const jsxCode = `const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;`;

  return (
    <div>
      <SyntaxHighlighter language="javascript">{jsCode}</SyntaxHighlighter>
      <SyntaxHighlighter language="python">{pyCode}</SyntaxHighlighter>
      <PrismLight language="jsx">{jsxCode}</PrismLight>
    </div>
  );
};

Popular Programming Languages

Coverage of widely-used programming languages with examples.

const PopularLanguagesDemo = () => {
  const languages = {
    javascript: `// Modern JavaScript with ES6+
const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];

const adults = users
  .filter(user => user.age >= 18)
  .map(user => ({ ...user, isAdult: true }));

const fetchUserData = async (userId) => {
  try {
    const response = await fetch(\`/api/users/\${userId}\`);
    return await response.json();
  } catch (error) {
    console.error('Failed to fetch user:', error);
    throw error;
  }
};`,

    python: `# Python with modern features
from typing import List, Dict, Optional
import asyncio
import aiohttp

class UserService:
    def __init__(self, base_url: str):
        self.base_url = base_url
    
    async def fetch_user(self, user_id: int) -> Optional[Dict]:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{self.base_url}/users/{user_id}") as response:
                if response.status == 200:
                    return await response.json()
                return None
    
    def process_users(self, users: List[Dict]) -> List[Dict]:
        return [
            {**user, 'full_name': f"{user['first_name']} {user['last_name']}"}
            for user in users
            if user.get('active', False)
        ]`,

    java: `// Modern Java with records and pattern matching
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public record User(String name, int age, boolean active) {}

public class UserProcessor {
    private final List<User> users;
    
    public UserProcessor(List<User> users) {
        this.users = users;
    }
    
    public List<User> getActiveAdults() {
        return users.stream()
            .filter(User::active)
            .filter(user -> user.age() >= 18)
            .collect(Collectors.toList());
    }
    
    public Optional<User> findUserByName(String name) {
        return users.stream()
            .filter(user -> user.name().equals(name))
            .findFirst();
    }
}`,

    rust: `// Rust with modern async and error handling
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use tokio;

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u64,
    name: String,
    email: String,
    active: bool,
}

#[derive(Debug)]
enum UserError {
    NotFound(u64),
    NetworkError(String),
    SerializationError,
}

struct UserService {
    client: reqwest::Client,
    base_url: String,
}

impl UserService {
    fn new(base_url: String) -> Self {
        Self {
            client: reqwest::Client::new(),
            base_url,
        }
    }
    
    async fn fetch_user(&self, id: u64) -> Result<User, UserError> {
        let url = format!("{}/users/{}", self.base_url, id);
        
        let response = self.client
            .get(&url)
            .send()
            .await
            .map_err(|e| UserError::NetworkError(e.to_string()))?;
            
        if response.status() == 404 {
            return Err(UserError::NotFound(id));
        }
        
        response
            .json::<User>()
            .await
            .map_err(|_| UserError::SerializationError)
    }
}`
  };

  return (
    <div>
      {Object.entries(languages).map(([lang, code]) => (
        <div key={lang} style={{ marginBottom: '2rem' }}>
          <h3>{lang.toUpperCase()}</h3>
          <SyntaxHighlighter language={lang} style={github}>
            {code}
          </SyntaxHighlighter>
        </div>
      ))}
    </div>
  );
};

Web Technologies and Markup

Specialized support for web development languages and markup formats.

const WebTechnologiesDemo = () => {
  const webLanguages = {
    jsx: `// React JSX with hooks and modern patterns
import React, { useState, useEffect, useCallback } from 'react';
import { useQuery, useMutation } from 'react-query';

interface User {
  id: number;
  name: string;
  email: string;
}

const UserProfile: React.FC<{ userId: number }> = ({ userId }) => {
  const [isEditing, setIsEditing] = useState(false);
  
  const { data: user, isLoading } = useQuery(
    ['user', userId],
    () => fetchUser(userId)
  );
  
  const updateMutation = useMutation(updateUser, {
    onSuccess: () => {
      setIsEditing(false);
      queryClient.invalidateQueries(['user', userId]);
    }
  });
  
  const handleSubmit = useCallback((formData: User) => {
    updateMutation.mutate(formData);
  }, [updateMutation]);
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div className="user-profile">
      <h2>{user?.name}</h2>
      {isEditing ? (
        <UserForm 
          user={user} 
          onSubmit={handleSubmit}
          onCancel={() => setIsEditing(false)}
        />
      ) : (
        <UserDisplay 
          user={user}
          onEdit={() => setIsEditing(true)}
        />
      )}
    </div>
  );
};`,

    scss: `// Modern SCSS with CSS Grid and Flexbox
@import 'variables';
@import 'mixins';

// CSS Custom Properties
:root {
  --primary-color: #{$primary-blue};
  --secondary-color: #{$secondary-green};
  --font-size-base: 16px;
  --spacing-unit: 8px;
  --border-radius: 8px;
  --transition-duration: 0.3s;
}

// Mixins
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

@mixin responsive-grid($min-width: 300px, $gap: 2rem) {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax($min-width, 1fr));
  gap: $gap;
}

// Component styles
.user-dashboard {
  @include responsive-grid(350px, 1.5rem);
  padding: calc(var(--spacing-unit) * 3);
  
  &__header {
    grid-column: 1 / -1;
    @include flex-center;
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    border-radius: var(--border-radius);
    color: white;
    padding: calc(var(--spacing-unit) * 2);
    
    h1 {
      margin: 0;
      font-size: calc(var(--font-size-base) * 1.75);
    }
  }
  
  &__card {
    background: white;
    border-radius: var(--border-radius);
    padding: calc(var(--spacing-unit) * 2);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform var(--transition-duration) ease;
    
    &:hover {
      transform: translateY(-2px);
    }
    
    @media (max-width: 768px) {
      padding: var(--spacing-unit);
    }
  }
}`,

    html: `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modern Web App</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="stylesheet" href="styles.css">
    <script type="module" src="app.js" defer></script>
</head>
<body>
    <header class="app-header">
        <nav class="navbar" role="navigation" aria-label="main navigation">
            <div class="navbar-brand">
                <img src="logo.svg" alt="Company Logo" width="120" height="40">
            </div>
            <ul class="navbar-menu" id="navbar-menu">
                <li><a href="#home" class="navbar-item">Home</a></li>
                <li><a href="#about" class="navbar-item">About</a></li>
                <li><a href="#services" class="navbar-item">Services</a></li>
                <li><a href="#contact" class="navbar-item">Contact</a></li>
            </ul>
            <button class="navbar-toggle" aria-controls="navbar-menu" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="hamburger"></span>
            </button>
        </nav>
    </header>
    
    <main class="main-content">
        <section class="hero" aria-labelledby="hero-title">
            <div class="container">
                <h1 id="hero-title">Welcome to Our Platform</h1>
                <p class="hero-subtitle">Build amazing things with our tools</p>
                <div class="hero-actions">
                    <button class="btn btn-primary">Get Started</button>
                    <button class="btn btn-secondary">Learn More</button>
                </div>
            </div>
        </section>
        
        <section class="features" aria-labelledby="features-title">
            <div class="container">
                <h2 id="features-title">Features</h2>
                <div class="features-grid">
                    <article class="feature-card">
                        <svg class="feature-icon" aria-hidden="true">
                            <use href="#icon-fast"></use>
                        </svg>
                        <h3>Lightning Fast</h3>
                        <p>Optimized for performance with modern web standards.</p>
                    </article>
                </div>
            </div>
        </section>
    </main>
    
    <footer class="app-footer">
        <div class="container">
            <p>&copy; 2023 Company Name. All rights reserved.</p>
        </div>
    </footer>
</body>
</html>`
  };

  return (
    <div>
      {Object.entries(webLanguages).map(([lang, code]) => (
        <div key={lang} style={{ marginBottom: '2rem' }}>
          <h3>{lang.toUpperCase()}</h3>
          <Prism language={lang} style={tomorrow}>
            {code}
          </Prism>
        </div>
      ))}
    </div>
  );
};

Configuration and Data Formats

Support for various configuration files and data interchange formats.

const ConfigurationFormatsDemo = () => {
  const configFormats = {
    yaml: `# Kubernetes Deployment Configuration
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp-deployment
  labels:
    app: webapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: nginx:1.21-alpine
        ports:
        - containerPort: 80
        env:
        - name: NODE_ENV
          value: "production"
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: database-secret
              key: url
        resources:
          limits:
            memory: "512Mi"
            cpu: "500m"
          requests:
            memory: "256Mi"
            cpu: "250m"
        readinessProbe:
          httpGet:
            path: /health
            port: 80
          initialDelaySeconds: 10
          periodSeconds: 5`,

    json: `{
  "name": "my-web-app",
  "version": "2.1.0",
  "description": "A modern web application",
  "main": "dist/index.js",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest",
    "test:coverage": "vitest --coverage",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "type-check": "tsc --noEmit"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.8.0",
    "@tanstack/react-query": "^4.24.0",
    "axios": "^1.3.0",
    "zustand": "^4.3.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.27",
    "@types/react-dom": "^18.0.10",
    "@vitejs/plugin-react": "^3.1.0",
    "vite": "^4.1.0",
    "typescript": "^4.9.0",
    "vitest": "^0.28.0",
    "@testing-library/react": "^13.4.0"
  },
  "engines": {
    "node": ">=16.0.0",
    "npm": ">=8.0.0"
  }
}`,

    dockerfile: `# Multi-stage Docker build for Node.js application
FROM node:18-alpine AS builder

# Set working directory
WORKDIR /app

# Copy package files
COPY package.json package-lock.json ./

# Install dependencies
RUN npm ci --only=production

# Copy source code
COPY . .

# Build application
RUN npm run build

# Production stage
FROM node:18-alpine AS production

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# Set working directory
WORKDIR /app

# Copy built application from builder stage
COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nextjs:nodejs /app/package.json ./package.json

# Switch to non-root user
USER nextjs

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
  CMD curl -f http://localhost:3000/health || exit 1

# Start application
CMD ["npm", "start"]`,

    toml: `# Rust Cargo.toml configuration
[package]
name = "web-server"
version = "0.3.0"
edition = "2021"
authors = ["Developer <dev@example.com>"]
description = "A high-performance web server built with Rust"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/web-server"
readme = "README.md"
keywords = ["web", "server", "async", "performance"]
categories = ["web-programming::http-server"]

[dependencies]
tokio = { version = "1.25", features = ["full"] }
axum = "0.6"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.6", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono"] }
uuid = { version = "1.3", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
clap = { version = "4.1", features = ["derive"] }

[dev-dependencies]
tokio-test = "0.4"
axum-test = "11.0"

[profile.release]
lto = true
codegen-units = 1
panic = "abort"`
  };

  return (
    <div>
      {Object.entries(configFormats).map(([lang, code]) => (
        <div key={lang} style={{ marginBottom: '2rem' }}>
          <h3>{lang.toUpperCase()}</h3>
          <Prism language={lang} style={tomorrow}>
            {code}
          </Prism>
        </div>
      ))}
    </div>
  );
};

Language Detection and Fallbacks

Handling unknown languages and providing fallback options.

/**
 * Language detection and fallback strategies
 */
interface LanguageDetectionOptions {
  /** Language identifier or 'text' for plain text */
  language?: string;
  /** Fallback to plain text for unsupported languages */
  fallbackToText?: boolean;
  /** Custom language detection function */
  detectLanguage?: (code: string) => string;
}

Language Detection Examples:

const SmartLanguageHighlighter = ({ code, language, ...props }) => {
  const [detectedLanguage, setDetectedLanguage] = useState(language);

  useEffect(() => {
    if (!language || language === 'auto') {
      // Simple heuristic language detection
      const detectLanguage = (code) => {
        if (code.includes('function') && code.includes('{')) return 'javascript';
        if (code.includes('def ') && code.includes(':')) return 'python';
        if (code.includes('class ') && code.includes('public')) return 'java';
        if (code.includes('<') && code.includes('>')) return 'html';
        if (code.includes('SELECT') || code.includes('FROM')) return 'sql';
        return 'text';
      };
      
      setDetectedLanguage(detectLanguage(code));
    }
  }, [code, language]);

  // Check if language is supported
  const isSupported = SyntaxHighlighter.supportedLanguages.includes(detectedLanguage);
  const finalLanguage = isSupported ? detectedLanguage : 'text';

  return (
    <div>
      {!isSupported && detectedLanguage !== 'text' && (
        <div style={{ color: 'orange', fontSize: '12px', marginBottom: '4px' }}>
          Language '{detectedLanguage}' not supported, showing as plain text
        </div>
      )}
      <SyntaxHighlighter 
        language={finalLanguage}
        {...props}
      >
        {code}
      </SyntaxHighlighter>
    </div>
  );
};

// Usage with automatic detection
const AutoDetectExample = () => {
  const codeSnippets = [
    'console.log("Hello, World!");',
    'print("Hello, World!")',
    'System.out.println("Hello, World!");',
    '<h1>Hello, World!</h1>',
    'SELECT * FROM users WHERE active = true;'
  ];

  return (
    <div>
      {codeSnippets.map((code, index) => (
        <SmartLanguageHighlighter 
          key={index}
          code={code}
          language="auto"
          style={github}
        />
      ))}
    </div>
  );
};

Custom Language Extensions

Adding support for domain-specific languages or extending existing language definitions.

const CustomLanguageExample = () => {
  // Register a custom language
  useEffect(() => {
    // Define custom SQL dialect
    const customSQL = {
      ...sqlLanguage,
      keywords: [
        ...sqlLanguage.keywords,
        'UPSERT', 'MERGE', 'WINDOW', 'PARTITION'
      ],
      functions: [
        ...sqlLanguage.functions,
        'LAG', 'LEAD', 'ROW_NUMBER', 'RANK', 'DENSE_RANK'
      ]
    };
    
    SyntaxHighlighter.registerLanguage('custom-sql', customSQL);
  }, []);

  const customSQLCode = `-- Advanced SQL with window functions
WITH monthly_sales AS (
  SELECT 
    DATE_TRUNC('month', sale_date) as month,
    SUM(amount) as total_sales,
    LAG(SUM(amount)) OVER (ORDER BY DATE_TRUNC('month', sale_date)) as prev_month_sales
  FROM sales
  WHERE sale_date >= '2023-01-01'
  GROUP BY DATE_TRUNC('month', sale_date)
),
growth_analysis AS (
  SELECT 
    month,
    total_sales,
    prev_month_sales,
    CASE 
      WHEN prev_month_sales IS NOT NULL 
      THEN ((total_sales - prev_month_sales) / prev_month_sales) * 100
      ELSE NULL
    END as growth_percentage,
    ROW_NUMBER() OVER (ORDER BY total_sales DESC) as sales_rank
  FROM monthly_sales
)
SELECT 
  month,
  total_sales,
  growth_percentage,
  sales_rank,
  CASE 
    WHEN sales_rank <= 3 THEN 'Top Performer'
    WHEN growth_percentage > 10 THEN 'High Growth'
    ELSE 'Standard'
  END as performance_category
FROM growth_analysis
ORDER BY month;`;

  return (
    <SyntaxHighlighter language="custom-sql" style={github}>
      {customSQLCode}
    </SyntaxHighlighter>
  );
};

Best Practices

Language Selection Strategy

const LanguageStrategy = {
  // Use Prism for modern web development
  webDevelopment: ['jsx', 'tsx', 'vue', 'svelte', 'graphql', 'mdx'],
  
  // Use highlight.js for general programming
  generalProgramming: ['python', 'java', 'cpp', 'csharp', 'go', 'rust'],
  
  // Both engines support these well
  common: ['javascript', 'typescript', 'css', 'html', 'json', 'yaml', 'sql'],
  
  // Specialized use cases
  specialized: {
    'data-science': ['python', 'r', 'julia', 'matlab'],
    'systems': ['c', 'cpp', 'rust', 'assembly'],
    'web': ['html', 'css', 'scss', 'jsx', 'vue'],
    'config': ['yaml', 'toml', 'ini', 'dockerfile']
  }
};

Performance Optimization

// Lazy load languages for better performance
const LazyLanguageLoader = ({ language, children, ...props }) => {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const loadLanguage = async () => {
      try {
        const lang = await import(`react-syntax-highlighter/dist/esm/languages/hljs/${language}`);
        SyntaxHighlighter.registerLanguage(language, lang.default);
        setIsLoaded(true);
      } catch (error) {
        console.warn(`Failed to load language: ${language}`);
        setIsLoaded(true); // Show as plain text
      }
    };

    if (!SyntaxHighlighter.supportedLanguages.includes(language)) {
      loadLanguage();
    } else {
      setIsLoaded(true);
    }
  }, [language]);

  if (!isLoaded) {
    return <pre style={{ opacity: 0.6 }}>{children}</pre>;
  }

  return (
    <SyntaxHighlighter language={language} {...props}>
      {children}
    </SyntaxHighlighter>
  );
};

Install with Tessl CLI

npx tessl i tessl/npm-react-syntax-highlighter

docs

async-builds.md

index.md

language-support.md

light-builds.md

prism-integration.md

standard-highlighter.md

styling-themes.md

tile.json