DEV Community

Nikhil
Nikhil

Posted on • Edited on

Build an In-Browser Transpiler

Recently I wanted to build an In-Browser transpiler for my react project. So in this article I will try to explain the process of building one.

Understanding Transpiling

Let us first understand what is transpiling?

Transpiling is nothing but process of converting your source code from one language to another. Transpiling is done by a software program called transpilers or source-to-source compilers.

Why do we need transpilers?

We know browser only understands javaScript. So transpilers helps us to write different languages, like CoffeeScript, TypeScript, or ClojureScript which during execution can be compiled to plain javaScript.

The most famous transpiler in javaScript world is Babel, but in this article we will use esbuild which I personally found out to be quite fast and it also allows us to do In-Browser bundling( will talk about this in future post๐Ÿ˜‰ ).

What are we building here?

We will be building a simple react application that will take the JSX code in textarea and will transpile the code into ES2015 javaScript.

Initializing

npx create-react-app react-transpiler
cd react-transpiler
npm install esbuild-wasm
Enter fullscreen mode Exit fullscreen mode

Node and npm should be preinstalled.

Building The App

After initializing, open the code editor at current path.

Index.js

import * as esbuild from "esbuild-wasm";
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

const App = () => {
  const ref = useRef<any>();
  const [input, setInput] = useState("");
  const [code, setCode] = useState("");

  const startService = async () => {
    ref.current = await esbuild.startService({
      worker: true,
      wasmURL: "https://unpkg.com/esbuild-wasm@0.8.27/esbuild.wasm",
    });
  };
  useEffect(() => {
    startService();
  }, []);

  const onClick = async () => {
    if (!ref.current) {
      return;
    }

    const result = await ref.current.transform(input, {
      loader: "jsx",
      target: "es2015",
    });

    setCode(result.code);
  };

  return (
    <div>
      <h2>JSX Transpiler</h2>
      <textarea
        value={input}
        style={{ height: "300px", width: "500px" }}
        onChange={(e) => setInput(e.target.value)}
      ></textarea>
      <div>
        <button onClick={onClick}>Transpile</button>
      </div>
      <pre>{code}</pre>
    </div>
  );
};

ReactDOM.render(<App />, document.querySelector("#root"));

Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Hurray๐ŸŽ‰๐ŸŽ‰

We built an In-Browser JSX transpiler using esbuild.

Wrap Up!

Thank you for your time!! Let's connect to learn and grow together. LinkedIn
Buy Me A Coffee

Top comments (0)