How to setup a React Environment using Webpack and Babel

React is a Javascript library, by Facebook, that is used for building user interfaces. It is a bomb 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:

Table of Contents

  • Pre-requisites
  • Getting Started
  • Webpack installation and configuration
  • Setting up Babel
  • Setting up our React Components
  • Html-Webpack-Plugin
  • Run it!
  • React, React, React
  • Conclusion
  1. Webpack - A module bundler
  2. Babel - A Javascript compiler
  3. ES6 - A relatively new Javasript standard
  4. Yarn - A package manager
  5. React - As expected

This article is best suited for beginners who aren’t afraid to get their hands dirty setting up a React environment from scratch.

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

Pre-requisites

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:

  • If you had already installed a package before, you can install it again without any internet connection. Apart from the fact that you can install packages offline, this also increases the speed of your installments.
  • The same exact dependencies are installed on any machine. This essentially means that an install on one machine will work the same exact way on any other machine.

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

Getting Started

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.

Webpack installation and configuration

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:

/*
    ./webpack.config.js
*/
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 interprate 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 set-up 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.

Setting up Babel

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:

/* 
    ./.babelrc
*/    
{
    "presets":[
        "es2015", "react"
    ]
}

That is it. Now when babel-loader is called in the webpack config file it knows what to do.

Setting up our React Components

So far our file structure looks like this:

.
|-- node_modules
|-- .babelrc
|-- package.json
|-- webpack.config.js
|-- yarn.lock

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

/*
    ./client/index.js
    which is the webpack entry file
*/
console.log('Hey guys and ladies!!')

Update index.html to:

/*
    ./client/index.html
    basic html skeleton
*/


  
    
    React App Setup
  
  
    

    
  


The index.html is the actual webpage which 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.

Html-Webpack-Plugin

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.

/* 
    ./webpack.config.js
*/
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.

Run it!

We are almost at the finish line. Let’s try run our setup. We just need to do one tiny thing first. Open up your package.json and let’s add a start script.

/*
    ./package.json
*/
{
  "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/](http://localhost:8080/). If you check your console you’ll see our message "Hey guys and ladies!!". The reason we use localhost:8080 is because webpack-dev-server serves all our files on port 8080. Notice webpack-dev-server is run when we execute our start script.

How to setup a React Environment using Webpack and Babel

Yay, it works. So let’s add a simple React Component and see what happens.

React, React, React

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 thats 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 extention on files that I intend to use JSX syntax.

Next let’s update the App.jsx file:

/*
    ./client/components/App.jsx
*/
import React from 'react';

export default class App extends React.Component {
  render() {
    return (
     
        # Hello World

      );
  }
}

Lastly, we render our component from our start file, index.js. Let’s replace the console.log() with:

/* 
    ./client/index.js
*/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';

ReactDOM.render(, document.getElementById('root'));

Open bash and start our project. Make sure your terminal reads that you are on the project root folder.

> yarn start

How to setup a React Environment using Webpack and Babel

There we go! Ecstatic that you got all the way to the end!!

Conclusion

We now have a working React Environment set-up. I hope that this tutorial shed 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 on the comment section.

Finally, you can and should try build up a more in depth React Project after the tutorial.

#reactjs #web-development #webpack #javascript

What is GEEK

Buddha Community

How to setup a React Environment using Webpack and Babel
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Riaan  Nkuna

Riaan Nkuna

1603813980

React Webpack Babel Setup From Scatch - React.js Tutorial

How to set up a complete React JS project from scratch. Using webpack and babel. I also show you how to add additional useful loaders such as file-loaders to import images, scss loaders to use scss and compile it into scss. I also show you how to make builds for multiple environment with environment variables.

Regex used in video:

/\.(js|jsx)$/
/\.html$/
/\.(png|jpe?g|gif)$/i
/\.s[ac]ss$/i
/\.(js|jsx|ts|tsx)$/

tsconfig.json file:
{
  "compilerOptions": {
    "target": "es5",
    "sourceMap": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": false,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "jsx": "react",
    "removeComments": true
  }
}

Github repo: https://github.com/daryanka/webpack-babel-tutorial

#react #webpack #babel

Joseph  Norton

Joseph Norton

1605145548

Django & React Tutorial #3 - React Integration Using Webpack & Babel

This Django and React tutorial covers how to integrate react with Django and perform all of the necessary setup steps. We will be using Webpack and Babel to bundle our React app and have the Django backend render a template that React will control.

📝 Series Code: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial
📕 Node.js & NPM: https://www.npmjs.com/get-npm

Code for Specific Files
babel.config.json: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/blob/main/Tutorial 1 - 4/frontend/babel.config.json
package.json: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/blob/main/Tutorial 1 - 4/frontend/package.json
webpack.config.json: https://github.com/techwithtim/Music-Controller-Web-App-Tutorial/blob/main/Tutorial 1 - 4/frontend/webpack.config.js

⌨ NPM Setup Commands ⌨

  • npm init -y
  • npm i webpack webpack-cli --save-dev
  • npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev
  • npm i react react-dom --save-dev
  • npm install @material-ui/core
  • npm install @babel/plugin-proposal-class-properties
  • npm install react-router-dom
  • npm install @material-ui/icons

#django #react #webpack #babel #web-development

Troy  Marvin

Troy Marvin

1604557500

React Webpack Babel Setup From Scatch - 2020 React.js Tutorial

How to set up a complete React JS project from scratch. Using Webpack and Babel. I also show you how to add additional useful loaders such as file-loaders to import images, scss loaders to use scss and compile it into scss. I also show you how to make builds for multiple environment with environment variables.

Regex used in video:

/\.(js|jsx)$/
/\.html$/
/\.(png|jpe?g|gif)$/i
/\.s[ac]ss$/i
/\.(js|jsx|ts|tsx)$/

tsconfig.json file:
{
  "compilerOptions": {
    "target": "es5",
    "sourceMap": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": false,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "jsx": "react",
    "removeComments": true
  }
}

Github repo: https://github.com/daryanka/webpack-babel-tutorial

#react #webpack #babel #javascript #developer

Talha Malik

Talha Malik

1615962751

Setup Webpack and Babel for React

If you always using Create React App(CRA) when working with React, maybe you have question like “how to setup and configuration Webpack and Babel for React application?”, So in this video we are going to learn that.

Webpack : https://webpack.js.org/

babel: https://babeljs.io/

code: https://github.com/candraKriswinarto/…

Subscribe: https://www.youtube.com/channel/UChspmksoHi3B9sKreATvpCA

#webpack #babel #react