React foundationSort Order

React: Setting up Babel Transpiler

In this episode we talk about why we need a transpiler. We then show you how to set up the babel transpiler in your project.

Setting up Babel

We can use babel in webpack by using the loaders. Let's install the babel-loader

npm install babel-loader babel-core babel-preset-es2015 --save-dev

The command above is going to setup babel in our project. The babel-preset-es2015 package is the part that will allow us to use es2015 syntax in our project. Babel supports many syntaxes for our project we will use 3 presets. So lets go ahead and install the other 2 we need.

npm install babel-preset-stage-0 babel-preset-react --save-dev

We also want to ensure that babel doesn't bloat our bundle code so we will install a package that will optimize the bundle size.

npm install babel-plugin-transform-runtime --save-dev

Once we have all the packages for babel we can add it to our webpack config. So now our webpack.config.js will look like the following.

module.exports = {  entry: "./entry.js",  output: {    path: __dirname,    filename: "bundle.js"  },  module: {    loaders: [      { test: /\.css$/, loader: "style!css" },      {         test: /\.(js|jsx)$/,        exclude: /(node_modules|bower_components)/,        loader: 'babel',        query: {          presets: ['es2015', 'stage-0', 'react'],          plugins: ['transform-runtime']        }      }    ]  }};

We can now use ES6+ syntax in our code lets try it out!

Trying out ES6+

Lets first start the webpack-dev-server with the following command.

webpack-dev-server --color --progress --watch

The --watch flag will make sure that webpack automatically re-compiles our bundle when we change it.

Now that we have webpack running in the background lets make some changes to our code. Add the following to entry.js

import "./style.css"document.write("Yay!");

Once this is done go ahead and boot up the page by heading over to localhost:8080 in the browser. Webpack will now serve our page and the bundle for us. You will also see the yellow background that we specified in the style.css from the previous episode.

Be sure to upgrade to get access to all react videos.