Contents
You may know that ReactJs is a Javascript library for creating client side interface. If you are already familiar with Html or Javascript, you can think about ReactJs as the alternate for the combined of Html and Javscript.
In the traditional way, when working on client side, we often follow these steps:
- Pre-rendered Html source from server side
- Using Css to decorator the page
- Using javascript/jquery if the page needs some effects or custom handler for user event
- Every time a page loaded, browser has to download the html from server side; this html source was the “bone” of the page, css and javascript only make the web beautifier
With ReactJs, the page html structure won’t depend on server side, it’s all about client side code. That means, the server only return a very short code, some time is just a few lines. These lines will load some javascript files; all the page structure and rendering is managed and process by these javascript files. ReactJs is a library that help us achieved that
In this tutorial, I aimed to give a basic ReactJs setup guide to the beginner, who is not familiar or have never worked with ReactJs
Let’s start!
1. Initializing ReactJs project
Create Nodejs based project folder
mkdir reactjs-basic
cd reactjs-basic
npm init -y
2. Install ReactJs required packages
Install ReactJs library packages
npm i react react-dom --save
Run above command should output this:
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN reactjs-basic@1.0.0 No description
npm WARN reactjs-basic@1.0.0 No repository field.
+ react@16.8.6
+ react-dom@16.8.6
added 8 packages from 3 contributors and audited 26 packages in 2.865s
found 0 vulnerabilities
3. Install Babel/Webpack
Hmmm! Now you may wonder what is Babel, what is Webpack and why we need them for our ReactJs project?
Webpack was developed as a module bundler, but now it was grown with a big plugin-system and can handle so many tasks during frontend development.
Babel is a toolchain that used to transform es6 code into es5 code. It is a life-saving for old browsers but can also work as a transformer for custom syntax.
We will go deep inside into Webpack and Babel, now we just need them for demonstrating our basic ReactJs setup
Install Babel
To install Babel and required transformer, run this command
npm i @babel/core babel-loader @babel/preset-env --save-dev
Because we are working with ReactJs so we need to install @babel/preset-react
npm i @babel/preset-react --save-dev
Create babel config file at project root and named .babelrc , update .babelrc file with the bellow content
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
Install Webpack
npm i webpack webpack-cli --save-dev
Update npm scripts so we can call Webpack bundle from command line. Add this to our package.json file, section scripts
"dev": "webpack --mode development"
Now our package.json file will look like this
{
"name": "reactjs-basic",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode development"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"webpack": "^4.36.1",
"webpack-cli": "^3.3.6"
}
}
Now you can run npm run build to test our Webpack command. An error will be thrown of course because Webpack does not have any thing to do with our project (we haven’t add any Code yet).
Webpack support config the build process through Webpack config file, the default config file must be named as webpack.config.js and located at our project root dir. Without this config file, Webpack can still work but it will use default Webpack config. In this case, we need to update Webpack config to make our sample app work
Create webpack.config.js file with this content
module.exports = {
entry: './src/index.jsx',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
Let me explain about the above code:
This webpack configuration file is quite simple, the exported object contains a rule. Webpack rule is an important part, it help Webpack to pick specific files and pass it to a transformer, a transformer is just a Babel loader.
In above configuration, we check for all js and jsx files, then pass it to babel-loader. Because the scan process also includes node_modules dir, so we will exclude it from test rule.
entry is the file that Webpack will check and transform first. If inside entry file we import or reference to other files, these files will also be transformed.
The preparing step was almost done, let’s create our first ReactJs file
1. Create src directory. Webpack default configuration will look for target files inside src dir, so we need it create it first
mkdir src
2. Create src/index.jsx file with bellow content
import React from 'react'
import ReactDom from 'react-dom'
ReactDom.render(
<h1>Cloudreports React Setup tutorial for beginer</h1>,
document.getElementById('root')
)
In above code, we pass 2 arguments in to ReactDom.render method
- The first argument is a React Component, we can pass a normal html element or React Custom Component here. We will talk about React Component in the next post, now we just focus on ReactJs project setup.
- The second argument is a html element, this is a real html node from our html dom with id attribute equal to root. In order to select existed element, we need a html page that contain this html element <div id=”root”></div>
We can imagine this rendering process as ReactJs will prepare Component passed at first argument, after that, it insert the result into html node that was passed in the second argument.
3. Run npm run build and we will get this output
> webpack --mode development
Hash: 3796f7f31cf91f6e2057
Version: webpack 4.36.1
Time: 455ms
Built at: 07/22/2019 11:06:10 PM
Asset Size Chunks Chunk Names
main.js 907 KiB main [emitted] main
Entrypoint main = main.js
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {main} [built]
[./src/index.jsx] 192 bytes {main} [built]
+ 11 hidden modules
When this command run completed, Webpack will create dist dir that contains our project build file, the Webpack default build file will be located at dist/main.js, we just need to link this build file into our blank html page.
Until now, the setup and build process was completed. But do you wondering how can we test this setup?
In real life projects, we have so many ways to test our ReactJs build file. But in the scope of this post, we will use the simplest way: Embed ReacJs build file inside a html page, let’s start testing:
1. Create index.html file at the root of this project with this content
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cloudreports ReactJs setup tutorial for beginer</title>
</head>
<body>
<div id="root"></div>
<script src="dist/main.js"></script>
</body>
</html>
2. We need a web server to serve this html file, let install one:
npm i serve -g
If this install finished with error, you can try again with sudo
now run serve:
serve .
we got this output
┌─────────────────────────────────────────────────┐
│ │
│ Serving! │
│ │
│ - Local: http://localhost:5000 │
│ - On Your Network: http://192.168.1.6:5000 │
│ │
│ Copied local address to clipboard! │
│ │
└─────────────────────────────────────────────────┘
Now open your browser and navigate to http://localhost:5000
If your browse display as bellow, then you have completed our ReactJs setup tutorial
if you got any error or something that prevent you from completing this tutorial, don’t hesitate to tell me by comment on this post.
In the next post, we will start creating our first React Component, thank you for reading!
References:
https://babeljs.io/docs/en/
https://webpack.js.org/concepts/
Git repo for this ReactJs setup tutorial
https://github.com/cloudreports/tutorial-reactjs-basic/tree/ReactJsBasicSetup
Discussion about this post