Webpack/Babel/React webapp (from scratch) with deployment on Heroku – Part II (Babel,React)

Part I here.

Haven’t done react before, so headed over to React’s getting started. And since I did not use create-react-app, that tutorial on add react in 1 min obviously does not apply..

But it’s really not too bad. 🙂 here we go!

Add Babel packages to transpile jsx code to regualr Javascript in the browser.

npm install --save-dev babel-loader @babel/core @babel/preset-env 

Install dependencies and create a babel config .babelrc in the root folder, and modify webpack.common.js

my-app
|- package.json
|- .babelrc
|- webpack.common.js
|- webpack.dev.js
|- webpack.prod.js
|- /dist
|- index.html
|- /src
|- index.js
|- print.js

In .babelrc write

{
  "presets": ["@babel/preset-env"]
}

In webpack.common.config

plugins: [
      new CleanWebpackPlugin(),
      ...
    ],
    resolve: {
        extensions: ['.js', '.jsx'],
    },
    module: {
      rules: [
        {
          test: /\.jsx$$/, 
          exclude: /node_modules/, 
          loader: "babel-loader"
        },
      ]
    },
    output: {...

Add more babel dependencies. Because babel uses very small helpers for common functions, by default this will be added to every file causing unnecessary duplication. Installing @babel/plugin-transform-runtime allows all helper functions to reference @babel/runtime module and reduce duplication across compiled output.

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

Now we add in React

npm install react react-dom @babel/preset-react

And update our .babelrc config

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Now we modify src/index.js to src/index.jsx and make some code adjustments to React’s syntax

import React from 'react';
import ReactDOM from 'react-dom';

const MyHeader = (props) => {
    return (<div onClick={(e) => {
        window.location.href = '/';
    }}><div>hey! We now have webpack, babel and react!</div></div>)
}

const App = () => {
    return (
    <div>
    <MyHeader></MyHeader>
    </div>);
}

ReactDOM.render(<App/>, document.getElementById('app'));

Lastly, add an index.html next to index.jsx

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title> React webpack babel</title>
    </head>
    <body>
        <div id="app"></div>
        </body>
</html>
npm run start

Your project directory should now look like this

my-app
|- package.json
|- .babelrc
|- webpack.common.js
|- webpack.dev.js
|- webpack.prod.js
|- /dist
|- /src
|- index.jsx
|- index.html

Next up head to heroku’s getting started to deploy your app on heroku

Github link to project
https://github.com/enerestar/react-webapp-heroku

Leave a Reply

Your email address will not be published. Required fields are marked *