How to set up a React project from scratch
Tags: javascript, react, javascripttips
Published: 2019-01-22 08:13:26

---
title: How to set up a React project from scratch
published: true
tags: javascript,reactjs,javascript-tips,react
canonical_url: https://medium.com/swlh/how-to-set-up-a-react-project-from-scratch-78261a9c2bbb
---

![](https://cdn-images-1.medium.com/max/1024/1*dy6J64BKcW0kHjWEuXgP7Q.png)

#### feature React course

- [Learn Pure React - An Interactive Deep Dive into the basics of React.js](https://www.educative.io/collection/5661736652767232/5629499534213120?affiliate_id=5312887308419072)

Despite the popularity of the React, setting up the application to begin with was a tough task. To fight this, the Facebook came with create-react-app that hid the complications, and exposed a working app to the end user. Today, take some time to understand the complexity of the easy react app!

Setting up all by yourself may not sound very practical and you should not do on many situations. However, it might be important to understand the things going inside. In case, if you don’t like create-react-app boilerplate some day, create your own boilerplate and begin every react project with it.

**Make sure you have installed:**

1. NodeJS
2. npm
3. terminal
4. a text editor

**Libraries to set up react from scratch:**

We’ll be using webpack and babel to set up react, and I don’t want you to get confused.

1. Babel is the compiler for next-generation JavaScript **.** It compiles newer JavaScript (ES6/7/8) to older ES5 standard to run the same on old and new browsers.
2. Webpack is a module bundler. We’ll use multi-directory and multi-file approach for easy management of the project. Webpack will bundle all our files into one, offering better performance and easier dependency management.

The setup revolves around these tools so we’ll get to the configuration in detail.

Let’s begin, fire up the mighty terminal!

```
mkdir react-from-scratchcd react-from-scratchnpm init -y
```

This creates a directory react-from-scratch and initializes the node project, the -y flag is used to skip all the questions with default answers.

Now that we have a directory to hold our project, let’s install react

npm install react react-dom

[view raw](https://gist.github.com/therj/f3ac87beea665037683ebea1d6d40536/raw/43d78bbd9cd6c70c286fe1007846d78fd3628892/install-react.sh)[install-react.sh](https://gist.github.com/therj/f3ac87beea665037683ebea1d6d40536#file-install-react-sh) hosted with

by [GitHub](https://github.com/)

This will install react and react-dom.

node\_modules folder will store all the modules and their dependencies.

package.json holds information about name, dependencies and more scripts.

package-lock.json is used for dependency integrity, there’s no ‘runs fine on my computer’.

### What isreact and react-dom?

react is the library that defines view components, the React components.

react-dom is the library that creates the view. react-dom is equivalent to the Web DOM. It creates and displays the web page.

The separation has allowed React to be used on multiple platforms with only changing the rendering library in place of react-dom. React Native renders for the iOS and the Android. ReactVR is for VR devices.

### Initializing Webpack development server

We have a way of creating and rendering React components now. We have yet to send these components to the browser to show them. This is what web server is used for.

npm install webpack webpack-dev-server webpack-cli — save-dev

[view raw](https://gist.github.com/therj/f3ac87beea665037683ebea1d6d40536/raw/43d78bbd9cd6c70c286fe1007846d78fd3628892/webpack-dev-server.sh)[webpack-dev-server.sh](https://gist.github.com/therj/f3ac87beea665037683ebea1d6d40536#file-webpack-dev-server-sh) hosted with

by [GitHub](https://github.com/)

The --save-dev flag saves these as the development dependencies. They won’t be a part of the final build that’s deployed on the server, they will be used for development process. webpack-cli is required to run the project from the terminal.

webpack must be installed because webpack-dev-server depends on it. This dev-server will live-reload our app.

### Creating a React app

In the root directory, which I named react-from-scratch, create a new file index.html. This will be the main file served to the browser.

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ReactJS Sample Project</title>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
```

- The react components will go in the div with id root.
- The script bundle.js will be created using webpack, which will contain all our react code, including react library and renderer, in proper format.

Create a file index.js, with the following code

```
import React from 'react';
import {render} from 'react-dom';

render(
  React.createElement("div", null, "Hello World"),
  document.getElementById("root")
);
```

React must be imported for a react app. render method is imported from react-dom using destructuring.

render takes two arguments: first one is the component and second one is the location.

React.CreateElement is a top-level React API. It creates elements, no JSX invloved.

Since it’s not very practical without JSX, we’ll replace it with </App> component later.

```
import React from 'react'
import { render } from 'react-dom'
import App from './containers/App'

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

document.getElementById("root") is our location on index.html.

### Setting up a Webpack development server

We have installed webpack, but we’re yet to make use of it.

Back in the terminal,

webpack-dev-server will compile our code fine and server at localhost:8080 than it’ll fail to find ./src.This is because webpack is expecting index.js at the ./src/ . Either you can move the index.js to src or modify the package.json file or set up the entry file in the webpack config file. Last option is most preferred and we’ll use the same without moving .

```
mkdir webpackcd webpacktouch webpack.dev.config.js
```

Create a directory webpack with a file webpack.dev.config.js.

Set the entry point in the webpack.dev.config.js

```
var webpack = require('webpack');
var path = require('path');

module.exports = {
entry: [
path.join(\_\_dirname, '../index.js')
]
}
```

It uses webpack as the dependency and sets entry point to index.js

We need to load the modules so modify the webpack.dev.config.js to

```
var webpack = require('webpack');
var path = require('path');

var parentDir = path.join(\_\_dirname, '../');

module.exports = {
    entry: [
        path.join(parentDir, 'index.js')
    ],
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
                exclude: /node\_modules/,
                loader: 'babel-loader'
            },{
                test: /\.less$/,
                loaders: ["style-loader", "css-loder", "less-loader"]
            }
        ]
    },
    output: {
        path: parentDir + '/dist',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: parentDir,
        historyApiFallback: true
    }
}
```

It contains a bunch of rules:

**Entry point**

index.js is the starting point for all scripts.

**The packages**

- babel-loader for loading jsx files.
- less-loader for loading less files
- less-loader requires less as a peer dependency.

Install all dependencies and peer dependencies with:

npm install --save-dev style-loader css-loader less-loader less

**The output**

The bundled file is named bundle.js and contained by dist directory.

**Development server**

The current directory is used as a base directory and.

### Setting up babel

We need babel to convert ES6 code to ES5.

Install babel and supporting libraries with

npm install --save-dev babel-cli babel-core babel-loader babel-plugin-transform-object-rest-spread babel-preset-es2015 babel-preset-react babel-preset-stage-0 babel-register

Configure the react app to make use of babel in package.json.

```
"babel": {
  "presets": ["es2015", "react", "stage-0"],
  "plugins": ["transform-object-rest-spread"]
}
```

It also uses a plugin to support rest/spread operator.

Make the changes to index.js, use App component instead of manually creating elements.

This is our new index.js

```
import React from 'react'
import { render } from 'react-dom'
import App from './containers/App'

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

Create ./containers/App.js file to serve the App

```
mkdir containerscd containerstouch App.js
```

Now fill the App.js with some basic React code

```
import React, {Component} from 'react';

class App extends Component {
    render () {
        return <p>Hello from the App!</p>
    }
}
export default App
```

We want to create a script that will run this react app for us.

```
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "dev": "./node\_modules/.bin/webpack-dev-server --config ./webpack/webpack.dev.config.js"
}
```

npm run dev will run the webpack-dev-server from the node modules with config file from ./webpack/webpack.dev.config.js.

This is what I get

npm run dev

![](https://cdn-images-1.medium.com/max/768/0*RF1O6oEmxZ4YGZ8t)

If you get a warning, add a mode in webpack config file to remove it.

Check the commented code mode: 'production', above. Other modes are 'develpment' and 'none'.

The default port is 8080.

![](https://cdn-images-1.medium.com/max/826/0*bzeU0FQJD5vUcL8-)

Tweak the configuration to your choices and enjoy your setup.

### Featured React JS Courses

#### [React 16 — The Complete Guide (incl. React Router 4 & Redux)](http://thebestdevlist.link/react-the-complete-16-guide-incl-redux)

4.7/5 Stars **||** 33.5 Hours of Video **||** 61,597 Students

Learn React or dive deeper into it. Learn the theory, solve assignments, practice in demo projects and build one big application which is improved throughout the course: The Burger Builder! [**Learn More.**](http://thebestdevlist.link/react-the-complete-16-guide-incl-redux)

[React 16 - The Complete Guide (incl. React Router 4 & Redux)](http://thebestdevlist.link/react-the-complete-16-guide-incl-redux)

#### Closing Notes:

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

[![](https://cdn-images-1.medium.com/max/1024/1*YqDjlKFwScoQYQ62DWEdig.png)](https://medium.com/swlh)

#### This story is published in [The Startup](https://medium.com/swlh), Medium’s largest entrepreneurship publication followed by +405,714 people.

#### Subscribe to receive [our top stories here](http://growthsupply.com/the-startup-newsletter/).

[![](https://cdn-images-1.medium.com/max/1024/1*ouK9XR4xuNWtCes-TIUNAw.png)](https://medium.com/swlh)

* * *