DEV Community 👩‍💻👨‍💻

tmhao2005
tmhao2005

Posted on • Updated on

How to test JSX directly on browsers without any building steps

Is there anytime you wonder that we have a React component written in ES6 style and you want to test it straight away on the browser without configuring babel to transform JSX and then configure webpack to bundle things?

If you have the same interest, here is the few steps helping you out.

First of all, we create the test website directory with the following structure:

website
- index.html
- index.js
- Foo.js
Enter fullscreen mode Exit fullscreen mode
  • with Foo.js is a simple component with following content:

export default () => <div>Foo</div>;

Enter fullscreen mode Exit fullscreen mode
  • index.js is all about importing and rendering:
import Foo from "./foo.js"; // can also use `foo`

ReactDOM.render(<Foo />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode
  • index.html this is the most important
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script
      src="https://unpkg.com/react@16/umd/react.production.min.js"
    ></script>
    <script
      src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
    ></script>
  </head>

  <body>
    <div id="root"></div>
    <script
      data-plugins="transform-es2015-modules-umd"
      type="text/babel"
      src="./foo.js"
    ></script>
    <script
      data-plugins="transform-es2015-modules-umd"
      type="text/babel"
      src="./index.js"
    ></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

There are couple of important things here:

We must include babel script for transpiling JSX and React + ReactDOM via CDN:

https://unpkg.com/babel-standalone@6/babel.min.js
https://unpkg.com/react@16/umd/react.production.min.js
https://unpkg.com/react-dom@16/umd/react-dom.production.min.js
Enter fullscreen mode Exit fullscreen mode

Next, we register a module by wrapping in <script type="text/babel" />, plus in order to support import from another module we have to use plugin transform-es2015-modules-umd by adding more data-plugins="transform-es2015-modules-umd". In this case we register 2 modules foo and index respectively so we can import foo module in index module.

That's it!

Top comments (2)

Collapse
 
ribosed profile image
ribosed • Edited on

Is this correct "react-dom.producti*m*on.min.js" .

Collapse
 
tmhao2005 profile image
tmhao2005

@ribosed you're right it was wording mistake :) I made the correction

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈