TypeScript Tutorial: Building a Simple Web-Based Code Syntax Highlighting Tool

In the world of web development, readability is king. Imagine staring at a wall of plain text code – a daunting task, right? Syntax highlighting solves this problem, transforming raw code into a visually appealing and easily understandable format. This tutorial will guide you through building a simple web-based code syntax highlighting tool using TypeScript. We’ll break down the concepts, provide practical examples, and equip you with the knowledge to create your own code-friendly application.

Why Syntax Highlighting Matters

Syntax highlighting isn’t just about aesthetics; it’s a crucial tool for developers. It enhances code readability by:

  • Visual Clarity: Different code elements (keywords, variables, strings, comments) are assigned distinct colors and styles, making it easier to scan and understand the code’s structure.
  • Error Detection: Highlighting can immediately point out syntax errors or inconsistencies, saving you valuable debugging time.
  • Improved Comprehension: By visually separating code components, syntax highlighting helps you grasp the logic and flow of the code more effectively.

Whether you’re a seasoned developer or just starting, a syntax highlighting tool will significantly improve your coding experience.

Setting Up Your Project

Let’s get started by setting up our project. We’ll use a simple HTML file, a TypeScript file, and a few basic CSS styles. Create a new directory for your project and add the following files:

  • index.html
  • style.css
  • main.ts
  • tsconfig.json (we’ll create this later)

Here’s a basic structure for your index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Syntax Highlighter</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <textarea id="code" rows="10" cols="80">
// Your code goes here
    </textarea>
    <div id="highlighted-code"></div>
    <script src="main.js"></script>
</body>
</html>

And here’s a basic style.css file:


body {
    font-family: monospace;
    background-color: #f0f0f0;
    margin: 20px;
}

textarea {
    width: 100%;
    margin-bottom: 10px;
}

.keyword {
    color: blue;
}

.string {
    color: green;
}

.comment {
    color: gray;
}

Now, let’s set up tsconfig.json. This file tells the TypeScript compiler how to compile your TypeScript code. Create this file in the root of your project directory and paste the following content:


{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["./src/**/*"]
}

This configuration specifies that we’re targeting ECMAScript 2015, using CommonJS modules, and outputting the compiled JavaScript files to a dist directory. The strict: true option enables strict type checking, which is highly recommended for writing robust TypeScript code. We’ve also set up esModuleInterop to allow us to import ES modules in a more compatible way.

Writing the TypeScript Code

The heart of our syntax highlighter lies in the TypeScript code. We’ll create a function that takes code as input, identifies different code elements, and applies appropriate styles. Open main.ts and let’s start writing our highlighting logic:


// Define the code and the DOM elements
const codeTextArea = document.getElementById('code') as HTMLTextAreaElement;
const highlightedCodeDiv = document.getElementById('highlighted-code') as HTMLDivElement;

// Regular expressions for different code elements
const keywordRegex = /b(function|if|else|for|while|return|const|let|var|class|import|export)b/g;
const stringRegex = /"([^"\]*(\.[^"\]*)*)"/g;
const commentRegex = ///.*|/*[sS]*?*//g;

// Function to highlight the code
function highlightCode() {
  if (!codeTextArea || !highlightedCodeDiv) {
    return;
  }

  let code = codeTextArea.value;

  // Highlight comments
  code = code.replace(commentRegex, '<span class="comment">$&</span>');

  // Highlight strings
  code = code.replace(stringRegex, '<span class="string">$&</span>');

  // Highlight keywords
  code = code.replace(keywordRegex, '<span class="keyword">$&</span>');

  // Set the highlighted code in the div
  highlightedCodeDiv.innerHTML = code;
}

// Add an event listener to the textarea
codeTextArea.addEventListener('input', highlightCode);

// Initial highlighting on page load
highlightCode();

Let’s break down this code:

  • Selecting DOM Elements: We start by getting references to the text area (where the user types the code) and the div element (where the highlighted code will be displayed).
  • Regular Expressions: We define regular expressions (regex) to match different code elements. Regex is a powerful tool for pattern matching in strings. Each regex is designed to find specific patterns:
    • keywordRegex: Matches common JavaScript keywords. The b ensures we match whole words.
    • stringRegex: Matches strings enclosed in double quotes. The ([^"\]*(\.[^"\]*)*) part is for escaping quotes inside strings.
    • commentRegex: Matches single-line and multi-line comments.
  • highlightCode() Function: This function is the core of our highlighter. It does the following:
    • Gets the code from the text area.
    • Uses the replace() method with our regex to find and replace the matched code elements with HTML spans that apply the appropriate CSS classes. The $& in the replace function represents the entire matched string.
    • Sets the innerHTML of the highlightedCodeDiv to the highlighted code.
  • Event Listener: We add an event listener to the text area so that the highlightCode() function is executed every time the user types something.
  • Initial Highlighting: We call highlightCode() once when the page loads to highlight any existing code in the text area.

Compiling and Running the Code

Now that our TypeScript code is ready, we need to compile it into JavaScript that the browser can understand. Open your terminal or command prompt and navigate to your project directory. Then, run the following command:


tsc

This command uses the TypeScript compiler (tsc) to compile your main.ts file. The compiled JavaScript file (main.js) will be created in the dist directory (as specified in tsconfig.json).

To run your code, open index.html in a web browser. You should see a text area where you can type your code, and a highlighted version of your code will appear below it. Try typing some JavaScript code, and you should see the keywords, strings, and comments highlighted according to the CSS styles we defined.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to fix them when building a syntax highlighter:

  • Incorrect Regular Expressions: Regex can be tricky. Make sure your regex patterns accurately match the code elements you want to highlight. Use online regex testers (like regex101.com) to test and debug your regex.
  • Missing CSS Styles: Ensure that your CSS styles are correctly defined and linked to your HTML file. If you don’t see any highlighting, double-check your CSS classes and selectors.
  • Incorrect DOM Element Selection: Make sure you are selecting the correct HTML elements using document.getElementById(). If you’re getting null, check that your HTML elements have the correct IDs and that the script is running after the elements are loaded.
  • Event Listener Issues: Ensure that your event listener is correctly attached to the text area. If the highlighting doesn’t update as you type, check the event listener and the highlightCode() function.
  • Compiler Errors: If you encounter compiler errors, carefully read the error messages. They often provide valuable clues about what’s wrong with your TypeScript code (e.g., type errors, syntax errors).

Enhancements and Next Steps

Our simple syntax highlighter provides a solid foundation. Here are some ideas for enhancements:

  • Support for More Languages: Extend the highlighter to support other programming languages (e.g., Python, Java, C++) by adding more regex patterns for their keywords, data types, and other syntax elements.
  • Theme Customization: Allow users to choose different color themes for the highlighting. You could provide a dropdown menu or a settings panel to switch between themes.
  • Line Numbers: Add line numbers to the highlighted code for easier navigation and debugging.
  • Code Folding: Implement code folding to allow users to collapse and expand code blocks (e.g., functions, loops), improving readability for large code files.
  • Error Highlighting: Integrate a code linter or parser to detect errors and highlight them in the code.
  • Automatic Indentation: Automatically indent the code as the user types, making the code more readable.

Key Takeaways

  • Syntax highlighting significantly improves code readability and comprehension.
  • TypeScript provides a robust type system and excellent tooling for building web applications.
  • Regular expressions are a powerful tool for pattern matching and are essential for syntax highlighting.
  • You can build a functional syntax highlighter with a few lines of code and some basic HTML, CSS, and JavaScript.
  • This project is a great starting point for exploring more advanced web development concepts.

FAQ

Here are some frequently asked questions about syntax highlighting:

  1. What is syntax highlighting? Syntax highlighting is a feature that visually distinguishes different elements of code (keywords, variables, strings, comments) using colors and other styles.
  2. Why is syntax highlighting important? It improves code readability, helps detect errors, and enhances overall code comprehension.
  3. What tools can I use to create a syntax highlighter? You can use HTML, CSS, JavaScript, and regular expressions. TypeScript can significantly improve the development experience. There are also many existing libraries, like Prism.js and highlight.js, that you can use.
  4. How do regular expressions work? Regular expressions are sequences of characters that define a search pattern. They are used to match and manipulate text.
  5. Can I use this highlighter for production code? While this tutorial provides a basic foundation, you may want to use a more feature-rich library (like Prism.js or highlight.js) for production environments, as they offer more advanced features and handle more edge cases.

This tutorial has walked you through creating a basic syntax highlighter in TypeScript. By using regular expressions and carefully managing your HTML and CSS, you can significantly enhance the readability of code. The techniques you learned here can be adapted to many other web development projects. Continue to experiment, learn, and build! The world of code awaits!