TypeScript Tutorial: Building a Simple Web-Based Code Formatter

In the world of web development, clean and readable code is king. It’s essential for collaboration, debugging, and maintaining your projects over time. Imagine working on a project with hundreds or thousands of lines of code, all formatted inconsistently! It quickly becomes a nightmare. This is where code formatters come in. They automatically tidy up your code, making it easier to read and understand. In this tutorial, we’ll dive into building a simple web-based code formatter using TypeScript. This project will not only teach you about TypeScript but also introduce you to the practical application of code formatting and the power of web development tools.

Why Build a Code Formatter?

While IDEs and code editors often have built-in formatting features, building your own offers several benefits:

  • Customization: You can tailor the formatting rules to your specific needs and coding style.
  • Learning: It’s a great way to understand how code formatting works under the hood.
  • Accessibility: A web-based formatter can be accessed from any device with a browser.
  • Collaboration: Share your formatter with your team to enforce consistent code style across projects.

By building this tool, you’ll gain hands-on experience with TypeScript, understand how to manipulate code programmatically, and learn to integrate external libraries to enhance functionality. This project will also improve your problem-solving skills and give you a practical understanding of how web applications are built.

Setting Up Your Project

Let’s get started by setting up our project. We’ll use the following tools:

  • TypeScript: The language we’ll be using.
  • HTML: For the structure of our web page.
  • CSS: For styling our web page.
  • Prettier (Optional): A code formatter we will integrate into our project to do the actual code formatting.

First, create a new project directory and navigate into it using your terminal:

mkdir code-formatter-tutorial
cd code-formatter-tutorial

Initialize a new npm project:

npm init -y

Next, install TypeScript and Prettier as dev dependencies:

npm install typescript prettier --save-dev

Now, let’s set up the TypeScript configuration file. Create a file named tsconfig.json in your project’s root directory and add the following configuration:

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

This configuration specifies that we want to compile TypeScript to ES5 JavaScript, use CommonJS modules, output the compiled files to a dist directory, and enable strict type checking. The include array tells the compiler to include all files in the src directory.

Creating the HTML Structure

Create an index.html file in your project’s root directory. This file will contain the basic structure of our web page:

<!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>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Code Formatter</h1>
    <textarea id="code-input" placeholder="Enter your code here"></textarea>
    <button id="format-button">Format Code</button>
    <textarea id="code-output" placeholder="Formatted code will appear here" readonly></textarea>
  </div>
  <script src="dist/index.js"></script>
</body>
</html>

This HTML sets up the basic layout: a title, two text areas (one for input, one for output), and a button to trigger the formatting. It also links to a style.css file for styling and includes our compiled JavaScript file (dist/index.js).

Styling with CSS

Create a style.css file in your project’s root directory and add some basic styles to make the page look presentable:

body {
  font-family: sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f4f4f4;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  width: 80%;
  max-width: 800px;
}

h1 {
  text-align: center;
  color: #333;
}

textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-family: monospace;
  resize: vertical;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #3e8e41;
}

This CSS provides a basic layout and styling for the HTML elements, making the page more user-friendly.

Writing the TypeScript Logic

Now, let’s write the TypeScript code that will handle the formatting. Create a directory named src in your project’s root directory. Inside the src directory, create a file named index.ts. This is where our main application logic will reside.

// Import Prettier
import prettier from "prettier";
import parserBabel from "prettier/parser-babel";

// Get references to HTML elements
const codeInput = document.getElementById("code-input") as HTMLTextAreaElement;
const formatButton = document.getElementById("format-button") as HTMLButtonElement;
const codeOutput = document.getElementById("code-output") as HTMLTextAreaElement;

// Function to format the code
async function formatCode() {
  if (!codeInput || !codeOutput) {
    console.error("Code input or output element not found.");
    return;
  }

  const code = codeInput.value;

  try {
    const formattedCode = await prettier.format(code, {
      parser: "babel", // You can change this based on the code type (e.g., "typescript", "json")
      plugins: [parserBabel], // Add parsers here.
      // Add any Prettier options you want here (e.g., tabWidth, printWidth)
      tabWidth: 2,
      printWidth: 80,
    });
    codeOutput.value = formattedCode;
  } catch (error) {
    console.error("Formatting error:", error);
    codeOutput.value = `Formatting error: ${error}`;
  }
}

// Add event listener to the button
formatButton?.addEventListener("click", formatCode);

Let’s break down this code:

  • Import Prettier: We import the Prettier library, along with the parser for Babel (which is used for JavaScript and JSX code).
  • Get HTML Elements: We retrieve references to the input and output text areas and the format button using their IDs. The as HTMLTextAreaElement and as HTMLButtonElement assertions are used to tell TypeScript the type of these elements.
  • formatCode Function: This function is the heart of our code formatter. It does the following:
    • Gets the code from the input textarea.
    • Uses prettier.format() to format the code. We pass in the code, the parser, and any desired Prettier options (like tabWidth and printWidth).
    • Displays the formatted code in the output textarea.
    • Handles any errors that occur during formatting and displays an error message.
  • Add Event Listener: We attach an event listener to the format button. When the button is clicked, the formatCode function is executed.

Compiling and Running the Code

Now that we have our TypeScript code, we need to compile it to JavaScript. Open your terminal in the project’s root directory and run the following command:

tsc

This command will use the tsconfig.json file to compile the TypeScript code in the src directory and output the compiled JavaScript files into the dist directory.

After successful compilation, you can open the index.html file in your browser. You should see the code formatter interface. Enter some code into the input text area, click the “Format Code” button, and the formatted code will appear in the output text area.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • Incorrect File Paths: Double-check that the file paths in your index.html (e.g., <script src="dist/index.js">) and style.css are correct.
  • Missing Dependencies: Make sure you have installed all the necessary dependencies (TypeScript, Prettier) using npm.
  • TypeScript Compilation Errors: If you encounter compilation errors, carefully read the error messages in the terminal. They usually indicate type mismatches, syntax errors, or other issues in your TypeScript code. Review your code and the tsconfig.json configuration.
  • Prettier Configuration: Ensure that your Prettier configuration in the prettier.format() options is correct. The parser option should match the type of code you are formatting (e.g., “babel” for JavaScript/JSX, “typescript” for TypeScript, “json” for JSON).
  • Browser Console Errors: Open your browser’s developer console (usually by pressing F12) and check for any JavaScript errors. These can provide valuable clues about what’s going wrong.
  • Prettier Not Formatting: If Prettier isn’t formatting, check the following:
    • Make sure you’ve installed Prettier correctly.
    • Verify that you’ve imported the correct parser for your code type (e.g., parserBabel).
    • Double-check your Prettier options (tabWidth, printWidth, etc.).

Advanced Features and Improvements

You can extend this project with various advanced features:

  • Support for Different Languages: Add support for formatting other languages like JavaScript, HTML, CSS, JSON, etc. by adding the correct Prettier parsers.
  • Configuration Options: Allow users to customize Prettier options like tab size, print width, and more through a settings panel.
  • Code Highlighting: Integrate a code highlighting library (e.g., Prism.js, highlight.js) to provide syntax highlighting in the input and output text areas.
  • Error Reporting: Improve error reporting to provide more informative error messages to the user.
  • Saving and Loading: Implement functionality to save and load code snippets.
  • Integration with Code Editors: Explore how to integrate your code formatter with popular code editors or IDEs.
  • Dark Mode: Add a dark mode toggle to improve the user experience.

These improvements will make your code formatter more versatile and user-friendly.

SEO Best Practices and Keyword Optimization

To ensure your tutorial ranks well on search engines like Google and Bing, it’s important to incorporate SEO best practices. Here’s how we’ve done it in this tutorial:

  • Keywords: We’ve naturally used relevant keywords such as “TypeScript,” “code formatter,” “web-based,” and “tutorial” throughout the article. The title also includes the primary keywords.
  • Headings and Subheadings: We’ve used clear headings (H2, H3, H4) to structure the content and make it easy for readers and search engines to understand the topics covered.
  • Short Paragraphs: We’ve broken down the information into short, concise paragraphs to improve readability.
  • Bullet Points: Bullet points are used to list key benefits, steps, and features, making the information scannable.
  • Meta Description: While not directly in the content, a well-crafted meta description (max 160 characters) on the HTML page will summarize the tutorial and encourage clicks from search results. A good example would be: “Learn how to build a simple web-based code formatter using TypeScript. This step-by-step tutorial covers setup, HTML, CSS, TypeScript code, and troubleshooting.”
  • Image Alt Text: When you include images, use descriptive alt text that includes relevant keywords.

Key Takeaways

  • You’ve learned how to set up a TypeScript project and compile TypeScript code.
  • You’ve gained experience with HTML, CSS, and JavaScript.
  • You’ve learned how to integrate external libraries (Prettier) into your project.
  • You’ve built a practical web-based tool that can improve your code quality and readability.
  • You’ve gained an understanding of the basics of code formatting and how it works.

FAQ

Here are some frequently asked questions about this tutorial:

  1. What is Prettier? Prettier is an opinionated code formatter that automatically formats your code to a consistent style. It supports many languages and is widely used in the web development community.
  2. Why use Prettier instead of manually formatting code? Manual formatting is time-consuming and prone to errors. Prettier automates the process, ensuring consistent formatting across your project and saving you time.
  3. Can I use this code formatter with other languages? Yes, you can. You’ll need to install the appropriate Prettier parser for the language you want to format (e.g., prettier/parser-html for HTML).
  4. How can I customize the formatting rules? You can customize Prettier’s formatting rules by passing options to the prettier.format() function. For example, you can set the tabWidth, printWidth, and other options.

Building this simple code formatter is a fantastic way to learn about TypeScript, front-end web development, and the importance of code quality. As you experiment with different languages, Prettier options, and features, you will gain a deeper understanding of how these tools work and how to apply them effectively. The ability to create your own tools can really enhance your development workflow, providing you with a better understanding of the underlying concepts and allowing you to customize your environment to suit your needs. The skills you learn here can be applied to many other projects, making you a more efficient and capable developer. Remember, the key to mastering any technology is practice and experimentation. Take what you’ve learned here, expand on it, and build something amazing!