skip to Main Content

How to run tsx files on a browser directly without compiling?

I thought it was impossible before. However recently I found a meta web site https://segment-anything.com/demo which has the tsx and scss files in the dev tool source.

enter image description here

And I think it’s really running the code since it’s in the run stack.

I have no idea how to do that.

2

Answers


  1. TSX is just JSX with typing. Typings are ignored by default.

    The easiest way to "run tsx files on a browser directly" is by including <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>.

    This technically does compile, but it’s done by the browser.

    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    
    <script type="text/babel">
      // "HTMLElement" is the typing of TSX
      const elem: HTMLElement = <div>Hello, World!</div>;
      console.log(elem);
    </script>
    

    For a valid HTML5 page, make sure to add:

    <!DOCTYPE html>
    <meta charset="utf-8" />
    
    <title>Title</title>
    
    Login or Signup to reply.
  2. I hope you’re doing well, Basically, Typescript is the superset of JavaScript, and browsers are not able to understand Typescript directly.
    If you want to run typescript code in the browser you want to compile it first.

    There are many ways to compile TypeScript. The most common way is to use the TypeScript compiler, which is included in the TypeScript distribution. To compile a TypeScript file.

    You can use ts-node package to execute TypeScript files from the command line.

    Still, if you want to learn about Typescript with a command line kindly follow this link.
    https://www.educative.io/answers/how-to-execute-the-typescript-file-using-the-command-line

    Thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search