TypeScript Tutorial: Creating a Simple Interactive Code Formatter

In the world of web development, clean and consistent code is paramount. It’s not just about making your code work; it’s about making it readable, maintainable, and collaborative. Imagine a scenario: you’re working on a project with a team, and everyone has their own coding style. This can lead to merge conflicts, confusion, and a general headache. This is where code formatting tools come to the rescue. They automatically standardize your code, ensuring everyone follows the same rules, making it easier to read and understand.

The Problem: Inconsistent and Unreadable Code

Developers often struggle with code formatting. Without a consistent style, codebases become difficult to navigate. Spaces, tabs, indentation, and line breaks can vary wildly, leading to:

  • Reduced readability: Code becomes harder to understand at a glance.
  • Increased debugging time: It takes longer to spot errors when code is poorly formatted.
  • Collaboration challenges: Merging code from different developers becomes more complex.
  • Difficulty in code maintenance: Updating and modifying code becomes time-consuming.

Manually formatting code is tedious and error-prone. It’s a task that can be easily automated, saving valuable time and effort. This tutorial will guide you through creating a simple, interactive code formatter using TypeScript, a typed superset of JavaScript, which will help you automate this process.

Why TypeScript?

TypeScript adds static typing to JavaScript, making your code more robust and easier to maintain. It catches errors early in the development process and provides better code completion and refactoring capabilities. These features are incredibly useful when working with code formatters, as they help you ensure the correctness of your formatting logic.

Step-by-Step Guide: Building Your Code Formatter

Let’s build a simple, interactive code formatter that takes JavaScript code as input and formats it to a consistent style. We’ll use the popular Prettier library under the hood for the actual formatting, but the focus will be on building an interactive interface and integrating Prettier into your TypeScript application.

1. Setting Up Your Project

First, create a new project directory and initialize it with npm (or yarn):

mkdir code-formatter
cd code-formatter
npm init -y

Next, install TypeScript, Prettier, and a few other necessary packages:

npm install typescript prettier @types/prettier --save-dev

Create a tsconfig.json file in your project root to configure the TypeScript compiler:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

2. Creating the HTML Interface

Create an index.html file with the following basic structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Formatter</title>
</head>
<body>
    <textarea id="code-input" rows="10" cols="80" placeholder="Enter your code here..."></textarea>
    <button id="format-button">Format Code</button>
    <pre id="formatted-code"><code></code></pre>

    <script src="./dist/index.js"></script>
</body>
</html>

This HTML provides a text area for code input, a button to trigger formatting, and a <pre> element to display the formatted code. The script tag includes the compiled JavaScript file that we will create in the next step.

3. Writing the TypeScript Code

Create an index.ts file in your project root and add the following code:

import prettier from 'prettier';

const codeInput = document.getElementById('code-input') as HTMLTextAreaElement;
const formatButton = document.getElementById('format-button') as HTMLButtonElement;
const formattedCode = document.getElementById('formatted-code') as HTMLPreElement;
const formattedCodeElement = formattedCode.querySelector('code') as HTMLElement;

async function formatCode() {
  if (!codeInput || !formatButton || !formattedCode || !formattedCodeElement) {
    console.error('One or more elements not found.');
    return;
  }

  const code = codeInput.value;
  try {
    const formatted = await prettier.format(code, {
      parser: 'babel',
      plugins: [], // You can add plugins here if needed
      // Add any other Prettier options here
    });
    formattedCodeElement.textContent = formatted;
  } catch (error) {
    console.error('Formatting error:', error);
    formattedCodeElement.textContent = `Formatting error: ${error}`;
  }
}

formatButton.addEventListener('click', formatCode);

Let’s break down this code:

  • We import the Prettier library.
  • We get references to the HTML elements using their IDs.
  • The formatCode function retrieves the code from the textarea, uses Prettier to format it, and displays the formatted code in the <pre> element.
  • We add an event listener to the format button that calls the formatCode function when clicked.
  • Error handling is included to catch formatting errors and display an appropriate message.

4. Compiling and Running the Code

Compile your TypeScript code using the TypeScript compiler:

tsc

This will generate a dist folder containing the compiled JavaScript file (index.js). Open index.html in your browser. You should see the text area, the