This tutorial is out of date and no longer maintained.
Note: You may wish to use Create React App as an alternative to setting up React Projects.
React is a JavaScript library, by Facebook, that is used for building user interfaces. It is a library that offers so many advantages but one of the biggest setbacks is the steep learning curve. When I started out, one of the things that bugged me a whole lot was that most of the tutorials skipped over the React environment set-up.
So here we go, this article is best suited for beginners who aren’t afraid to get their hands dirty setting up a React environment, from scratch. My number one mission is to keep this article simple and easy to understand. I will not use any boilerplates and you can find the whole set-up on my GitHub repo here. We will be using the following:
Note: Article updated for webpack 2.
By the end of the tutorial, we will have set up a working React environment and just for fun, we will have a simple webpage displaying Hello World.
Brace yourselves for some fun!
We require Yarn and Node pre-installed on our machines before we dive into the project.
As mentioned above we’ll use Yarn Package Manager. It is quite similar to npm and has almost the same commands provided by npm. It also comes with a few extra features that npm does not provide. Just to catch you up, a few of the main reasons I use yarn are:
For more information, you could go over the Yarn documentation.
For Mac Os users, the commands below will suffice to install Yarn and because I got all your backs, anyone using any other OS can head on over to the Yarn installation page to get the right instructions on installation.
- brew update
- brew install yarn
Open your terminal and create a new folder. You can name it as you wish. Navigate into the folder and initialize the project by running yarn init
. yarn init
just like npm init
will give you a few prompts, just press enter
till the end or configure it as you’d like to.
- mkdir hello-world-react
- cd hello-world-react
- yarn init
When yarn init
is finished you will notice in your folder, in this case, ‘hello-world-react’, you’ll have a new file package.json
just like if you had done npm init
.
Next, we need to install webpack and a few dependencies.
- yarn add webpack webpack-dev-server path
Inside ‘hello-world-react’ a new file yarn.lock
is created. This file is what Yarn uses to lock down the exact dependencies to use on another machine, you don’t really have to worry about this file as it is automatically generated.
Now that we have webpack installed we need a config file to give it instructions on what to do. Create a new file, webpack.config.js
, on the project folder and open it on your preferred text editor.
- touch webpack.config.js
We can then update the configuration file:
const path = require('path');
module.exports = {
entry: './client/index.js',
output: {
path: path.resolve('dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{ test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader"
}, {
test: /\.jsx?$/,
exclude: /node_modules/,
use: "babel-loader"
}
]
}
}
Basically, to get a running instance of webpack we need to specify an entry
point and an output
.
entry
: Specifies the entry file where the bundler starts the bundling process.output
: Specifies the location where the bundled JavaScript code is to be saved.We, however, also have loaders. These are needed because we want the browser we use to be able to interpret and run JSX code (for React) and code written in ES6.
loaders
: They are transformations that are applied on a file in our app.The loaders
key property takes in an array of loaders. For our basic setup, we specified that the babel-loader
goes through and transpiles every file that ends with a .js
or .jsx
extension excluding the files inside the node_modules
folder. You could always add more loaders as needed. For example, if you had separate style sheets in your project you’d require a CSS loader. All these loaders can be found in the webpack documentation. Feel free to test them out.
In our webpack configuration, we specified that we are using a babel-loader
. Where does this babel-loader
come from you ask? Well, we need to install it and later set a few configurations.
- yarn add babel-loader babel-core babel-preset-es2015 babel-preset-react --dev
Those are all the dependencies we need for Babel. Notice we have installed babel-preset-es2015
and babel-preset-react
, presets are Babel plugins that simply tell Babel what to look out for and transform into plain, vanilla JavaScript.
We then have to configure Babel and we can do this in a new file which we’ll name .babelrc
.
- touch .babelrc
Then we can update the file to:
{
"presets":[
"es2015", "react"
]
}
That is it. Now when babel-loader
is called in the webpack config file it knows what to do.
So far our file structure looks like this:
.
|-- node_modules
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock
It’s high time we add the React side don’t you think? We’ll create a new folder client
and add an index.js
file and an index.html
file.
- mkdir client
- cd client
- touch index.js
- touch index.html
- cd ..
Now we have this:
.
|-- client
|-- index.html
|-- index.js
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock
Next, we need to add some code. We’ll start out with something simple just to verify that our set-up so far works.
Open up index.js
and add:
console.log('Hey folks!')
Update index.html
to:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React App Setup</title>
</head>
<body>
<div id="root">
</div>
</body>
</html>
The index.html
is the actual webpage that loads our React Components on the browser. I mentioned before that we need babel
in order to compile our code into a syntax that browsers support. We code our React components using JSX
and in our case, we will also use ES6
. The syntax of these two modules is not supported by most browsers therefore, we have to run this code through the babel loaders
, and then the bundled output is what we’ll specify to be displayed on index.html.
One way to add the bundled file to our HTML is to insert a script
tag and pass the location of the bundled file into the script tag. A better way to do this is to use this nifty package called html-webpack-plugin
. It provides an easy way to have all your HTML generated for you. All you need is the standard HTML skeleton and it’ll take care of your script insertions with just a few configurations. Let’s do that next.
First, we’ll install the plugin. Make sure your terminal is currently reading you’re root project folder, hello-world-react
, then enter the following command:
- yarn add html-webpack-plugin
Then open up your webpack.config.js and add a few configurations.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './client/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
...
module: {
rules: [
...
]
},
// add this line
plugins: [HtmlWebpackPluginConfig]
}
The configuration is pretty self-explanatory. We require the html-webpack-plugin
and then create a new instance of it, and set our skeleton HTML as the template
. filename
refers to the name of the HTML that the plugin will generate. inject
body tells the plugin to add any JavaScript into the bottom of the page, just before the closing body
tag.
We are almost at the finish line. Let’s try running our setup. We just need to do one tiny thing first. Open up your package.json
and let’s add a start script.
{
"name": "hello-world-react",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
// add the scripts key to your package.json
"scripts": {
"start": "webpack-dev-server"
},
"dependencies": {
...
},
"devDependencies": {
...
}
}
Now we can go to our terminal and run:
- yarn start
Open your browser on http://localhost:8080/
. If you check your console you’ll see our message "Hello folks!"
. The reason we use localhost:8080 is that webpack-dev-server
serves all our files on port 8080
. Notice webpack-dev-server
is run when we execute our start script.
Yay, it works. So let’s add a simple React Component and see what happens.
I’ll do a very basic Hello World React Component. We need to install React dependencies first.
- yarn add react react-dom
Next, in the client
folder we can add a folder named components
and create a file App.jsx
.
- cd client
- mkdir components
- cd components
- touch App.jsx
- cd ../..
So our file structure now looks like this:
.
|-- client
|-- components
|-- App.jsx
|-- index.html
|-- index.js
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock
While naming component files in React the convention is to use PascalCase
that’s why our file name starts with a capitalized letter. The extension could be either .jsx
or .js
, I find it better to explicitly use the .jsx
extension on files that I intend to use JSX
syntax.
Next let’s update the App.jsx
file:
import React from 'react';
export default class App extends React.Component {
render() {
return (
<div style={{textAlign: 'center'}}>
<h1>Hello World</h1>
</div>);
}
}
Lastly, we render our component from our start file, index.js
. Let’s replace the console.log()
with:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(<App />, document.getElementById('root'));
Open bash and start our project. Make sure your terminal reads that you are on the project root folder.
- yarn start
There we go! Ecstatic that you got all the way to the end!!
We now have a working React Environment set-up. I hope that this tutorial sheds some light on what the configurations really do and why we need them. Also, if the set-up is a bit too tasking to do on every project you can always fork my repo and have a base to start from.
Please feel free to experiment around with different webpack configurations and hit me up with any cool things you’ve discovered in the comment section.
Finally, you can and should try to build up a more in-depth React Project after the tutorial. Cheers!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!