DEV Community

kris
kris

Posted on • Originally published at Medium on

How to set up a React project from scratch

feature React course

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 rawinstall-react.sh hosted with

by GitHub

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 rawwebpack-dev-server.sh hosted with

by GitHub

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 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

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.

Tweak the configuration to your choices and enjoy your setup.

Featured React JS Courses

React 16 — The Complete Guide (incl. React Router 4 & 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.

React 16 - The Complete Guide (incl. React Router 4 & Redux)

Closing Notes:

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

This story is published in The Startup, Medium’s largest entrepreneurship publication followed by +405,714 people.

Subscribe to receive our top stories here.


Top comments (1)

Collapse
 
geratarra profile image
Gerardo Tarragona Serna

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

No \ character needed after node:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "./node_modules/.bin/webpack-dev-server --config ./webpack/webpack.dev.config.js"
}