Set Up React App with WebPack and Babel

In this blog you will learn to set up a React Application:

  • Using create-react-app
  • Using Webpack, Webpack Dev Server and Babel from scratch

I am assuming that you have Node installed already on your system.

Using create-react-app

We will first install the create-react-app globally. Then we create a project using create-react-app command.

npm install -g create-react-app
create-react-app projectname
cd projectname
npm run start

And then all we have to do is just run npm run start . And that’s it. That’s all you have to do to set up your React application.

Using Webpack, Webpack Dev Server and Babel from scratch

The former was simple right. However, let’s learn how we can set up our React App from scratch.

Step 1: Create package.json file

cd ~
mkdir projectname
cd ~/projectname
// Creates package.json file
npm init --yes

Step 2: Install react and react-dom

npm i react react-dom

Step 3: Install Babel

Let’s install babel and the required presets and plugins.

npm i -D @babel/preset-react @babel/preset-env @babel/core babel-loader @babel/plugin-proposal-class-properties

@babel/preset-react is preset for react,
@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms are needed by your target environment(s).
@babel/core contains the core functionality of Babel.
babel-loader will be used by webpack to transpile Modern JS into the JS code that browsers can understand.
Since all browsers don’t understand javascript’s static class properties feature @babel/plugin-proposal-class-properties plugin transforms static class properties as well as properties declared with the property initializer syntax.

Step 4: Create a babel config file .babelrc

Here we tell babel to use @babel/preset-env target the last few versions of browsers and support for them. This will ensure that when the browser is updated it will stop transpiling of the old browser version and will transpile for the new one.
modules: false
 means hey babel! don’t do anything with the modules let webpack handle it.
We also tell webpack to use @babel/preset-react for React and @babel/plugin-proposal-class-properties to transform static class properties

{
"presets": [
[ "@babel/preset-env", {
"modules": false,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 Firefox versions",
"last 2 Safari versions",
"last 2 iOS versions",
"last 1 Android version",
"last 1 ChromeAndroid version",
"ie 11"
]
}
} ],
"@babel/preset-react"
],
"plugins": [ "@babel/plugin-proposal-class-properties" ]
}

Step 5: Install Webpack and Webpack Dev Server

npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin path

Step 6: Create directories and files for the project

Create directories calledsrc and public .Create our HTML file public/index.htm , entry filesrc/index.js and a component file src/App.jsinside of it.

mkdir src public
touch src/index.js src/App.js public/index.html

Step 7: Set up Webpack configuration file webpack.config.js

Here html-webpack-plugin will use your custom index.html that will be rendered by webpack-dev-server
Please note that if you don’t pass any param in new HTMLWebpackPlugin() , then thehtml-webpack-plugin plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags.

Also add the style loader, css loader and file-loader for styles and images. As webpack understands javascript so we need to convert the styles and images in javascript using these loaders

npm install style-loader css-loader file-loader

const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );

module.exports = {
    context: __dirname,
    entry: './src/index.js',
    output: {
        path: path.resolve( __dirname, 'dist' ),
        filename: 'main.js',
        publicPath: '/',
    },
    devServer: {
        historyApiFallback: true
     },
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: /node_module/,
                use: 'babel-loader'
            },
            {
                test: /\.css?$/,
                use: [ 'style-loader', 'css-loader' ]
            },
            {
                test: /\.(png|j?g|svg|gif)?$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve( __dirname, 'public/index.html' ),
            filename: 'index.html'
        })
    ]
};

Notice that we have also passed historyApiFallbackto true and public path to ‘/’
What it does is that it redirect all server requests to /index.html which will download all the JS resources and allow React Router to take it from there.
If we don’t do this then when you add routes later using react-router or @reach/router and if you access a route like /dashboard , the browser will make a GET request to /dashboard which will fail, as you have no logic on the server to handle that request.

So publicPath allows you to specify the base path for all the assets within your application. historyAPIFallback will redirect 404s to /index.html.

Step 7: Create a React Component src/App.js

Create a class inside src/App.js and export it

import React from 'react';
class App extends React.Component {
render() {
return(
<div>
My App Component
</div>
);
}
}
export default App

Step 8: Create a div#root inside public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="main.js"></script></body>
</html>

Step 9: Insert App.js component into the DOM

Now let’s insert the App.js component into div with the id root that exists public/index.html file

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";

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

Step 10: Add scripts in the package.json

"scripts": {
"webpack-dev-server": "webpack-dev-server",
"dev": "webpack-dev-server --mode=development",
"prod": "webpack --mode=production"
},

Now run the webpack dev server.

npm run dev
1+

Leave a Reply