Skip to content

Latest commit

 

History

History
188 lines (153 loc) · 4.66 KB

jsx.md

File metadata and controls

188 lines (153 loc) · 4.66 KB

JSX

About JSX

JSX is an XML-like syntax extension to ECMAScript. It allows you to mix HTML and JavaScript.

JSX is not part of the ECMAScript standard, but using the appropriate tooling we can compile our JavaScript/JSX code into JavaScript browsers understand.

JSX looks like this:

<div>
  <h1>Hello.</h1>
  <button onclick={() => alert("Hi")}>Click</button>
</div>

For an in-depth introduction to JSX, see the official documentation.

Setup

We'll use a compiler to transform JSX into h(tag, data, children) function calls and a bundler to create a single file we can deliver to the browser.

In a new directory, create an index.html file:

<!doctype html>
<html>

<body>
<script src="bundle.js"></script>
</body>

</html>

And an index.js file:

import { h, app } from "hyperapp"

app({
  state: "Hi.",
  view: state => <h1>{state}</h1>
})

Install dependencies:

npm i -S hyperapp

Install development dependencies:

npm i -D \
  babel-plugin-transform-react-jsx \
  babel-preset-es2015 \
  babelify \
  browserify \
  bundle-collapser \
  uglifyify \
  uglifyjs

Create a .babelrc file:

{
  "presets": ["es2015"],
    "plugins": [
      [
        "transform-react-jsx",
        {
          "pragma": "h"
        }
      ]
    ]
}

Bundle the application:

$(npm bin)/browserify \
  -t babelify \
  -g uglifyify \
  -p bundle-collapser/plugin index.js | uglifyjs > bundle.js

Install development dependencies:

npm i -D \
  webpack \
  babel-core \
  babel-loader \
  babel-preset-es2015 \
  babel-plugin-transform-react-jsx

Create a .babelrc file:

{
  "presets": ["es2015"],
    "plugins": [
      [
        "transform-react-jsx",
        {
          "pragma": "h"
        }
      ]
    ]
}

Create a webpack.config.js file:

module.exports = {
  entry: "./index.js",
  output: {
    filename: "bundle.js",
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: "babel-loader"
    }]
  }
}

Bundle the application:

$(npm bin)/webpack -p

Install development dependencies:

npm i -D \
  rollup \
  rollup-plugin-babel \
  rollup-plugin-node-resolve \
  rollup-plugin-uglify \
  babel-preset-es2015-rollup \
  babel-plugin-transform-react-jsx

Create a rollup.config.js file:

import babel from "rollup-plugin-babel"
import resolve from "rollup-plugin-node-resolve"
import uglify from "rollup-plugin-uglify"

export default {
  plugins: [
    babel({
      babelrc: false,
      presets: ["es2015-rollup"],
      plugins: [
        ["transform-react-jsx", { pragma: "h" }]
      ]
    }),
    resolve({
      jsnext: true
    }),
    uglify()
  ]
}

Bundle the application:

$(npm bin)/rollup -cf iife -i index.js -o bundle.js