Setting up reactjs environment & first reactjs app(hello-world)

  • Reactjs is used to build high-performance user interfaces.
  • It is a component based JavaScript web framework.
  • Every component is a JavaScipt object.
  • It uses "jsx" syntax. It should be compiled to get acctual JavaScript code.
  • We can re-use the components of one application in other applications.

Before we are starting the reactjs app we should know about Node Package Manager in short "npm".

npm: It is a package manager for the JavaScript programming language. npm is also a default package manager for  nodejs. To install npm we have to install nodejs.

Installing nodejs in ubuntu

# 1. Add NodeJs PPA
$ sudo apt-get install python-software-properties
$ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
# 2. Install NodeJs and NPM
$ sudo apt-get install nodejs
# 3. Now, check the version of NodeJS and NPM
$ node -v
$ npm -v

Let's talk about the tools (JavaScript packages)  that we use to develop ReactJs Application.

  1. Babel:
    • Babel is a JavaScript transpiler that converts the "JSX" code to normal JavaScript code.
    • Browsers don't understand the "JSX" syntax that's why we convert it into normal JavaScript code.
    • Basic Babel packages:
      • ​babel-core: It contains the Node API and "require" hook.
      • babel-loader: It is used to transpile the jsx into JavaScript
      • babel-preset-es2015: It  is used to enable ES2015(ES6) code compilation down to ES5
      • babel-preset-react: It is used to optimize the react code.
  2. Webpack:
    • Webpack is a npm package that is used to bundle the static assets like css, JavaScript, images, fonts, etc.
    • We use components in react. Every component uses JavaScript file, css file, images, fonts separately. Webpack gathers all these files and bundles them.
    • It's a good development approach to split up the static files based on the components, Because we can easily remove components and its related files.
    • Packages used with webpack:
      • webpack: It is used to bundle the splitted files into a single file based on its type.
      • ​html-webpack-plugin: It creates a html5 file and inserts the bundled JavaScript files into the html5 file with script tag just before the end of the body tag. 
      • extract-text-webpack-plugin: It moves all the required *.css/*.less/*.sass modules in entry chunks into a bundled CSS file based on the configuration.
      • style-loader: It creates style nodes from JS strings.
      • css-loader: It translates CSS into CommonJS.
      • less-loader: It compiles the less into CSS.
      • sass-loader:  It compiles the sass into CSS.
      • webpack-dev-server: It is a little Node.js Express server used to serve a webpack bundle. It renders the every change that is made to react components.

ReactJs Environment Setup:

  • Create a directory with the application name (react-hello-world). Open the terminal and move to the directory & run the command "npm init".
  • It will ask you questions like package name, version, description, entry point , test command, git repository, keywords, author, license.
  • You can answer those questions or skip it by pressing "Enter" key. After that, it will create a file "package.json" .
  • package.json used to store our package information like dependency packages, command line scripts, etc.
  • Now, install react dependency packages from npm with below command
    • npm install --save react react-dom
  • Install babel packages from npm with below command
    • npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
  • Install webpack & its related packages from npm with below command.
    • npm install --save-dev webpack webpack-dev-server html-webpack-plugin 
      npm install --save-dev css-loader style-loader extract-text-webpack-plugin
  • If you observe our application directory. It contains "package.json" and "node_modules" directory. "node_modules" directory contains all the packages that we installed through npm.
  • Now, create a configuration file for webpack "webpack.config.js" inside our application directory. And add the below configurations to it.
    • var HTMLWebpackPlugin = require('html-webpack-plugin');
      var ExtractTextPlugin = require('extract-text-webpack-plugin');
      
      var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
          template: __dirname + '/src/index.html',
          filename: 'index.html',
          inject: 'body'
      })
      var ExtractTextPluginConfig = new ExtractTextPlugin({
          filename: 'main.css',
          disable: false,
          allChunks: true
      })
      
      module.exports = {
        entry: __dirname + '/src/index.js',
        module:{
          loaders: [
             {
               test: /\.js$/,
               exclude: /node_modules/,
               loader: 'babel-loader'
             },
             {
               test: /\.css$/,
               loader: ExtractTextPlugin.extract({
                 fallback: 'style-loader',
                 use: 'css-loader'
               })
             }
          ]
        },
        output:{
          filename: 'bundle.js',
          path: __dirname + '/build/'
        },
        plugins: [
          HTMLWebpackPluginConfig,
          ExtractTextPluginConfig
        ]
      };
      
      
  • In webpack config file we export the configuration settings as a json object. It contains keys "entry", "module", "output", "plugins".
    • entry takes a path of index.js file as a value
    • module takes an object as value which contains "loaders", "pre loaders", "post loaders".
    • loaders takes a list of loader objects that are used to transpile the code (css, javascript, etc).  In our webpack.conf we have used "babel-loader" , "style-loader" and "css-loader".
    • every loader object has keys "test", "exclude" and "loader".
    • "test" takes a regular expression and finds all the files with the given extension.
    • "exclude" takes the directory path as a value and tells loader not to look for files in the directory.
    • "loader" takes a string as a value and transpiles the code from all the modules.
    • "output" has two keys "filename" and "path".  "filename" takes a string as value and represents the name of a bundle. "path"  it takes string as value and represents the path where the bundle will go.
    • "plugins" it takes a list of configurations of plugins that we use while developing the application.
    • Now, create ".babelrc" and add below code to it. It will help babel to compile the code down to the es5/es6 based on the presets init.
      • {
          presets: [
        	'react',
        	["es2015",  {"modules": false}]
         ]
        }
        
    • Create a directory "src" inside our application (react-hello-world)  with file "index.js" init.
    • Now, write our very first react component "Hello" in "index.js".
      • var React = require("react");

        var ReactDOM = require("react-dom");

        require('./main.css')

        class Hello extends React.Component {

            render(){
                return (
                    <h1> Hello World</h1>
                )
            }
        }

        ReactDOM.render(
          <Hello/>,
          document.getElementById('id_container')
        );

    • create a html file inside the directory "src"  and add below code init.
      • <html>
           <head>
              <title> Hello React App</title>
           </head>
           <body>
             <div id="id_container">

             </div>
           </body>
        </html>

  • Before run the application open "package.json" and replace the line "test": "echo \"Error: no test specified\" && exit 1"  with  "start": "webpack -p && webpack-dev-server --port 3000".
  • Now, open your browser and access "http://localhost:3000" you will see "Hello world".
  • our project structure looks like below.
  • project-name(react-hello-world)/
    |---------node_modules/
    |---------src/
    |           |------ index.js
    |           |------ index.html
    |           |------ main.css 
    |--------- package.json
    |--------- webpack.config.js
    |--------- .babelrc
    

Posted On 16 January 2019 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
How to drag and drop multiple files using Dropzone.js

Dropzone is a free open source library which makes a HTML element as dropzone, which enables user to drag files on to that area and ...

Continue Reading...
Google Analytics Graphs to your Dashboard in Python Web Frameworks

Ecommerce solution providers like OpenCart, Magento Provide extensions to see Google analytics data in their own dashboards as graphs. whereas there are no such plugins ...

Continue Reading...
Using CasperJS to scrape website data

CasperJS can be used for Navigation Scipting, Scraping and testing. In this Tutorial we will see how to scrape data from website using CasperJS and ...

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties