HTML5, CSS3, jQuery, JSON, Responsive Design...

React without build steps - Babel Standalone

Michael Brown   January 19 2017 02:00:05 PM
When I got started with React, over two years ago now, we had the JSX compiler tools.  All you had to do was load this JavaScript library into your HTML file, along with the React JavaScript library itself, of course, and you were done.  All of the React transpilation took place on the fly, within the browser itself.  Easy!

I don't know what I'd have done if I'd been told that to start with React you need to install Node and NPM, then spend two hours fiddling about with your Webpack config file before you can write a line of your application code.  Something tells me though that I would not have had a positive reaction!  Unfortunately, that's largely what new developers are told to do now, since Facebook deprecated the JSX Tools in favour of Babel, and then the latter dropped their own in-browser transpilation tool (browser.js) in Babel 6.

Fortunately, help is at hand in the shape of Babel Standalone.  To set it up, you simply add the babel.js (or babel.min.js) library to your HTML as a script tag, just after your main React and ReactDom script libraries.  Then, when loading your own JavaScript library (see simple-list.jsx in the code below) you set it type to "text/babel", then add any transpilations in the script tag's data-presets property.

That's it; you're done!!:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>babel-standalone Hello World example</title>

<div id="main"></div>
<script src="//"></script>
<script src="//"></script>
<script src="//"></script>

<script type="text/babel" data-presets="es2015, react, stage-2" src="js/simple-list.jsx"></script>

Here's the contents of that simple-list.jsx file:
const MyListElement = ({ listElement }) => (

class MyList extends React.Component {
render() {
const { listArray } = this.props;
const list = => {
return <MyListElement listElement={member} />;
          <h2>Man in the High Castle Characters</h2>
          <ul>{ list }</ul>

var myObj = window.myObj || {};
myObj.listArray = ["Joe Blake", "Juliana Crane", "John Smith", "Frank Fink"];

      title={myObj.title} />,

It's a very simple app, which just displays a list of characters from Amazon's superb adaptation of Philip K Dick's The Man in the High Castle.  I've implemented two React components here: MyListElement as a function component, and MyList as a full ES6 class.  (I know that  both could have been implemented as function components, since they don't require any React life cycle hooks, but I wanted to show how Babel Standalone handles both component types.)  Demo here.

You don't get module bundling/loading, of course, because Babel is not a module loader; you'll need Webpack or Browserify for that.  So you'll have to manage the script tag order yourself, and that's a pain.  But for getting devs started, that's not a show stopper in my book.
No Comments Found