TypeScript Tutorial: Build a Simple Web-Based Markdown Previewer

In the world of web development, the ability to transform raw text into formatted content is a common need. Markdown, a lightweight markup language, makes this process easier by allowing users to write content using a simple syntax that can then be converted into HTML. This tutorial will guide you through building a simple web-based Markdown previewer using TypeScript, providing a practical application of TypeScript’s features while addressing a real-world problem: enabling users to see a live preview of their Markdown text.

Why Build a Markdown Previewer?

Markdown is widely used for its simplicity and readability. It’s used in platforms like GitHub, Reddit, and many blogging systems. A Markdown previewer allows users to:

  • See how their Markdown will look as HTML without needing to publish.
  • Quickly format text using Markdown syntax and immediately see the results.
  • Improve the efficiency of content creation by providing instant feedback.

This tutorial will not only teach you how to build such a previewer but also give you hands-on experience with TypeScript, a superset of JavaScript that adds static typing. This will help you write more robust and maintainable code.

Prerequisites

Before you start, make sure you have the following:

  • A basic understanding of HTML, CSS, and JavaScript.
  • Node.js and npm (Node Package Manager) installed on your system.
  • A code editor like Visual Studio Code (VS Code).

Setting Up the Project

Let’s start by setting up our project. Open your terminal or command prompt and create a new directory for your project:

mkdir markdown-previewer
cd markdown-previewer

Initialize a new Node.js project:

npm init -y

This command creates a `package.json` file in your project directory. Now, let’s install TypeScript and a few other necessary packages:

npm install typescript --save-dev
npm install marked

Here’s what these commands do:

  • `typescript`: Installs TypeScript as a development dependency.
  • `marked`: Installs the `marked` library, which is a popular Markdown parser.

Next, initialize a TypeScript configuration file:

npx tsc --init

This command creates a `tsconfig.json` file, which allows you to configure how TypeScript compiles your code. You can customize this file based on your project’s needs. For this tutorial, you can stick with the default configuration. However, you might want to uncomment and modify the `outDir` option to specify where the compiled JavaScript files will be output.

Creating the HTML Structure

Now, let’s create the basic HTML structure for our Markdown previewer. Create a file named `index.html` in your project directory and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown Previewer</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="input-section">
            <textarea id="markdown-input" placeholder="Enter Markdown here..."></textarea>
        </div>
        <div class="preview-section">
            <div id="preview"></div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

This HTML provides:

  • A `textarea` element for users to input Markdown.
  • A `div` element (`preview`) to display the rendered HTML.
  • Links to a CSS file (`style.css`) for styling and a JavaScript file (`script.js`) for the functionality.

Styling with CSS

Create a `style.css` file in your project directory and add the following CSS to style the basic layout:

body {
    font-family: sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

.container {
    display: flex;
    height: 100vh;
}

.input-section {
    flex: 1;
    padding: 20px;
}

.preview-section {
    flex: 1;
    padding: 20px;
    border-left: 1px solid #ccc;
    background-color: #fff;
    overflow-y: scroll;
}

textarea {
    width: 100%;
    height: 90%;
    padding: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    resize: none;
}

#preview {
    padding: 10px;
    line-height: 1.6;
}

This CSS styles the layout with two sections: the input area and the preview area. It also provides basic styling for the `textarea` and the preview `div`.

Writing the TypeScript Code

Now, let’s write the TypeScript code that will make our Markdown previewer functional. Create a file named `script.ts` in your project directory and add the following code:

import { marked } from 'marked';

// Get the textarea and preview elements from the DOM
const markdownInput = document.getElementById('markdown-input') as HTMLTextAreaElement;
const preview = document.getElementById('preview') as HTMLDivElement;

// Function to update the preview
function updatePreview() {
  if (markdownInput && preview) {
    const markdownText = markdownInput.value;
    const html = marked.parse(markdownText);
    preview.innerHTML = html;
  }
}

// Add an event listener to the textarea to update the preview on input
if (markdownInput) {
  markdownInput.addEventListener('input', updatePreview);
}

// Initial render on page load
updatePreview();

Let’s break down this code:

  • Import `marked`: We import the `marked` library to parse the Markdown text.
  • Get DOM Elements: We retrieve the `textarea` and the `preview` `div` from the HTML using their IDs. The `as` keyword is used for type assertions, ensuring TypeScript knows the types of these elements.
  • `updatePreview` Function: This function takes the text from the `textarea`, uses `marked.parse()` to convert it to HTML, and then sets the `innerHTML` of the `preview` element to the resulting HTML.
  • Event Listener: An event listener is added to the `textarea` to call the `updatePreview` function whenever the user types something in the `textarea`.
  • Initial Render: The `updatePreview` function is called initially to render any default content or empty content when the page loads.

Compiling and Running the Application

To compile the TypeScript code, run the following command in your terminal:

tsc

This command will compile `script.ts` and generate a `script.js` file in the same directory (or the directory specified in your `tsconfig.json`).

Now, open `index.html` in your web browser. You should see the `textarea` and the preview area. As you type Markdown in the `textarea`, the preview area should update in real-time. If it doesn’t, double-check the file paths in your `index.html` and ensure that your code is free of typos.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • Incorrect File Paths: Ensure that the paths to `style.css` and `script.js` in `index.html` are correct.
  • Typos: Double-check for typos in your HTML, CSS, and TypeScript code, especially when referencing element IDs or class names.
  • Missing Imports: Make sure you’ve imported the `marked` library correctly.
  • Console Errors: Open the browser’s developer console (usually by pressing F12) to check for any JavaScript errors. These errors can provide valuable clues about what’s going wrong.
  • CORS Errors: If you’re loading the HTML from a file on your local machine, you might encounter CORS (Cross-Origin Resource Sharing) errors, which can prevent the JavaScript from running. To resolve this, you can either serve the files from a local web server (e.g., using `python -m http.server` in the project directory) or configure your browser to allow local file access.

Enhancements and Further Development

Now that you have a basic Markdown previewer, you can add more features and enhancements:

  • Syntax Highlighting: Integrate a syntax highlighter (e.g., Prism.js or highlight.js) to color-code the code blocks in the preview.
  • Toolbar: Add a toolbar with buttons for common Markdown formatting options (e.g., bold, italic, headings).
  • Custom Styles: Allow users to customize the CSS styles of the preview area.
  • File Upload: Enable users to upload Markdown files and preview them.
  • Error Handling: Implement error handling to gracefully handle invalid Markdown input or other potential issues.
  • Themes: Add a theme switcher to allow users to switch between light and dark modes.

Key Takeaways

  • You’ve learned how to build a basic Markdown previewer using TypeScript.
  • You’ve gained practical experience with TypeScript, including types, imports, and event listeners.
  • You’ve used the `marked` library to parse Markdown.
  • You’ve created a simple but functional web application.

FAQ

  1. How do I install the `marked` library?

    You install the `marked` library using npm: `npm install marked`.

  2. How do I compile the TypeScript code?

    You compile the TypeScript code using the command: `tsc`.

  3. Where do I put the HTML, CSS, and JavaScript files?

    You can put the files in the same directory. Make sure the paths in your `index.html` file are correct.

  4. What is the purpose of the `tsconfig.json` file?

    The `tsconfig.json` file configures the TypeScript compiler, allowing you to customize how your TypeScript code is compiled.

  5. Can I use this previewer with other Markdown libraries?

    Yes, you can modify the code to use any Markdown parsing library you prefer, such as Remark or Markdown-it.

Building this Markdown previewer provides a solid foundation for understanding how TypeScript can be used to create interactive web applications. As you expand the features and explore other Markdown libraries, you’ll gain a deeper appreciation for the power and flexibility of TypeScript in web development. The ability to see your Markdown rendered instantly is a boost to productivity, and this small project demonstrates how to achieve that. With each feature added, you not only enhance the tool but also solidify your understanding of TypeScript, making you more confident in your ability to tackle more complex projects in the future. The simplicity of this project belies the valuable skills and understanding it provides.