Skip to content

0xhjohnson

Setup React, Babel 7, and Webpack 4

React, Webpack, Babel2 min read

Create react app makes it extremely easy to get up and running with React providing sensible defaults. However, you're going to reach a point where you need to, or might just plain want to, setup from scratch.

“code that you cannot trust is code that you do not understand. The reverse is true also: code that you don’t understand is code you can’t trust.”- Kyle Simpson, Functional-Light JavaScript

Prerequisites

Before we begin you must install your package manager of choice, npm ships by default with node.js. I will be using yarn throughout this tutorial.

Setup

Lets begin by create a new directory to house our React application and initialize a package.json file to manage our dependencies etc...

mkdir default && cd default && yarn init -y

Install Babel

Babel requires a few packages to transpile JSX code properly.

yarn add @babel/core @babel/cli @babel/preset-env @babel/preset-react babel-loader -D

Create Babel config file

We are now ready to create a .babelrc config file. This is where we will tell Babel to use the plugins we just installed.

Install Webpack

Webpack requires just a couple of packages to get started.

yarn add webpack webpack-cli webpack-dev-server html-webpack-plugin html-webpack-template -D

Create Webpack config file

Webpack 4 does not require a config file but in the majority of cases you will want to use one. We are going to create a webpack.config.js file to store our config. This config specifies that our source files are located in the /src directory and outputs our Javascript bundle to /dist directory as bundle.js. The HtmlWebpackPlugin creates our index.html file in /dist and includes the script tag to out bundle.

Add scripts to package.json

We are now ready to define some npm scripts to run Webpack which is going to use Babel to transpile our code.

Create index.js file inside src

Let's go ahead and test our config by creating a Javascript file containing a basic React component. Make a folder named /src that will house all of our source files. Include some code in /src/index.js that will serve as the entry point for our application. Since we specified an appMountId in our Webpack config we can render our app component to the element with id app. We also need to install React and React-DOM.

yarn add react react-dom

Finally we need to start our dev server and test our config.

yarn run start:dev