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

In the world of web development, the ability to quickly write, test, and share code is invaluable. Whether you’re a seasoned developer or just starting your coding journey, a functional code editor can significantly boost your productivity. Imagine having a simple, yet effective, code editor right in your browser. This tutorial will guide you through building precisely that: a web-based code editor with syntax highlighting using TypeScript, a language that brings structure and reliability to your JavaScript projects. We’ll explore the core concepts, address common pitfalls, and provide you with a solid foundation for further customization and expansion.

Why TypeScript?

Before we dive in, let’s talk about why we’re using TypeScript. TypeScript is a superset of JavaScript that adds static typing. This means you can specify the data types of variables, function parameters, and return values. This provides several benefits:

  • Early Error Detection: TypeScript catches errors during development, rather than at runtime.
  • Improved Code Readability: Types make your code easier to understand and maintain.
  • Enhanced Tooling: TypeScript provides better autocompletion, refactoring, and other features in your IDE.
  • Reduced Bugs: Static typing helps prevent common JavaScript errors.

In essence, TypeScript helps you write more robust and maintainable code, making it an excellent choice for this project.

Project Setup

Let’s get started by setting up our project. We’ll use a basic HTML file, a TypeScript file, and some dependencies. Here’s what you need:

  1. Node.js and npm (or yarn): Make sure you have Node.js and npm (Node Package Manager) or yarn installed on your system.
  2. Create a Project Directory: Create a new directory for your project (e.g., `code-editor`).
  3. Initialize npm: Open your terminal, navigate to your project directory, and run `npm init -y` (or `yarn init -y`) to initialize a `package.json` file.
  4. Install TypeScript: Install TypeScript as a development dependency: `npm install typescript –save-dev` (or `yarn add typescript –dev`).
  5. Create `tsconfig.json`: Create a `tsconfig.json` file in your project root. This file configures the TypeScript compiler. You can generate a basic one by running `npx tsc –init`. Modify it to your liking, for example, setting the `target` to `ES2015` or higher.
  6. Create HTML File: Create an `index.html` file in your project directory.
  7. Create TypeScript File: Create a `src` directory, and within it, create a file named `app.ts`. This is where we’ll write our TypeScript code.

Basic HTML Structure

Let’s set up the basic HTML structure for our code editor. Open `index.html` and add the following code:

“`html

Simple Code Editor

body {
font-family: monospace;
margin: 0;
height: 100vh;
display: flex;
flex-direction: column;
}
#editor-container {
flex-grow: 1;
display: flex;
}
#code-editor {
width: 100%;
height: 100%;
padding: 10px;
border: 1px solid #ccc;
font-family: monospace;
white-space: pre-wrap;
overflow-x: auto;
resize: none;
}
#output-container {
width: 50%; /* Adjust as needed */
padding: 10px;
border: 1px solid #ccc;
overflow-y: scroll;
}
#output {
white-space: pre-wrap;
}


“`

This HTML provides a basic structure with a `


```

  • Add CSS for Line Numbers: Add some CSS to the `` tag in `index.html` to style the line numbers container:

    ```css
    #line-numbers {
    width: 40px;
    padding: 10px;
    border-right: 1px solid #ccc;
    background-color: #f0f0f0;
    overflow: hidden;
    text-align: right;
    user-select: none;
    }
    ```

  • Modify TypeScript: In `src/app.ts`, add the following code to generate the line numbers:

    ```typescript
    const lineNumbers = document.getElementById('line-numbers') as HTMLDivElement;

    function updateLineNumbers() {
    if (!codeEditor || !lineNumbers) return;
    const lines = codeEditor.value.split('n');
    let lineNumbersHTML = '';
    for (let i = 1; i <= lines.length; i++) {
    lineNumbersHTML += `

    ${i}

    `;
    }
    lineNumbers.innerHTML = lineNumbersHTML;
    }

    function updateOutput() {
    if (!codeEditor || !output) return;
    const code = codeEditor.value;
    const highlightedCode = highlightSyntax(code);
    output.innerHTML = highlightedCode;
    updateLineNumbers(); // Call here
    }

    codeEditor?.addEventListener('input', () => {
    updateOutput(); // Call updateOutput on input
    updateLineNumbers(); // Also update line numbers
    });

    updateLineNumbers(); // Initial update
    ```

  • Explanation:
    • We get a reference to the `lineNumbers` div.
    • The `updateLineNumbers` function splits the code into lines, creates the line number HTML, and updates the `lineNumbers` div's `innerHTML`.
    • We call `updateLineNumbers()` in `updateOutput()` and also attach it to the `input` event listener to keep the line numbers synchronized with the code in the editor.
    • We also call `updateLineNumbers()` on initial page load.
  • Compile and Test: Compile your TypeScript code (`npx tsc`) and refresh your browser. You should now see line numbers next to your code in the editor.
  • This is a simplified implementation. You might want to adjust the styling and behavior to match your preferences. Consider adding features like scrolling synchronization between the line numbers and the code editor.

    Key Takeaways

    In this tutorial, we've covered the fundamentals of building a web-based code editor with syntax highlighting using TypeScript. You've learned how to set up the project, write basic HTML and TypeScript code, compile the code, and run the application. We've also discussed common mistakes and how to fix them, and provided step-by-step instructions for adding line numbers. By understanding these core concepts, you can now start building more advanced features and customizing the editor to meet your specific needs. Remember that this is a starting point; the possibilities for enhancing your code editor are endless.

    FAQ

    1. Can I use this code editor for real-world projects?

      This basic code editor is a good starting point for learning. For production use, you'll likely want to integrate a more feature-rich code editor library (e.g., CodeMirror, Monaco Editor) to handle more complex features, performance optimizations, and language support.

    2. How can I add support for different programming languages?

      To support different languages, you'll need to use a syntax highlighting library that supports those languages (e.g., Prism.js, highlight.js). You'll also need to modify your code to select the correct language and apply the appropriate syntax highlighting rules.

    3. How do I handle errors and warnings in the code editor?

      You can integrate a linter (like ESLint) to analyze the code and display errors and warnings in the editor. You'll need to set up the linter, configure it for your project, and then display the errors in the user interface.

    4. What are some other features I can add?

      Other features include auto-completion, code formatting, themes, saving and loading code, and real-time compilation/execution.

    5. Is it possible to use this editor in a mobile app?

      Yes, you can embed this code editor in a mobile app using a web view component. However, you may need to optimize the editor for mobile devices, such as by adjusting the font size and touch interactions.

    Building a web-based code editor is a valuable learning experience. It combines several important aspects of web development, including HTML, CSS, JavaScript (and TypeScript), and DOM manipulation. You can extend this project in numerous ways, such as adding more advanced features or supporting more programming languages. The key is to start small, experiment, and learn from your mistakes. Embrace the iterative process of development, and don't be afraid to try new things. With each feature you add, you'll not only improve the editor but also your understanding of web development principles. Happy coding!

    More posts