JSX, Babel and Webpack: The Magic Behind ReactJS

Creating an app in React is a true pleasure, especially coming from programming interactive apps in vanilla JavaScript. React utilizes an object oriented design pattern, with a couple of core concepts that are unique: first, there are components. A component in React is a class which represents an element (or set of elements) in the DOM, which have properties (or props) and can also carry state. State in a React component is reserved for properties that may change over time: the text input on a form, for example, or a button which toggles text displayed to the user. Components are typically separated into discrete files, following the convention ComponentName.js.

The second feature which is distinct to React is JSX. JSX — or JavaScript XML — is a syntax extension to standard JavaScript which allows us to incorporate XML-like syntax into our code. For example, with JSX we are allowed to write the following:

const greeting = <h1>Hello, World!</h1>

This is where things start to get interesting. If you are familiar with HTML, the above should look familiar. With standard JavaScript, however, something like the following would be required to achieve the same result:

const greeting = document.createElement("h1");
greeting.innerText = "Hello, World!";

How exactly does this work and why is it legal? As it turns out, JSX is actually transpiled into standard JavaScript behind the scenes. React uses a preprocessor called Babel to translate our code before it is rendered in the browser. If we head over to the Babel REPL, we can see exactly how our code will be converted:

const greeting = React.createElement("h1", null, "Hello, World!");

This should look familiar! The main difference here is that React uses its own copy of the DOM — the virtual DOM — in order to dynamically handle component loading and unloading (or mounting, in React terminology.)

So, how does React incorporate Babel? This is where Webpack comes in. Webpack is a package bundler for JavaScript that compiles modules into a single source, which is then rendered in the browser. As of ES6, JavaScript introduced the import and export keywords, allowing us to separate out our code into discrete modules and include dependencies. Remember the mention of components being split up into separate files? Webpack first determines the file hierarchy for the project and generates a dependency graph. From the dependency graph it compiles the code to a single source, using Babel to translate and remove the import and export statements, and convert JSX into standard JavaScript.

Let’s create a simple React app to tie all of these concepts together. In your terminal, navigate to your root development directory. Then type:

npx create-react-app my-app

The create-react-app tool does a few things for us, including running npm init and installing Babel and Webpack with some configuration scripts. Let’s move into our new project directory and remove all of the generated source files (as we will create our own from scratch):

cd my-app && rm src/*
touch src/index.js

We will next create a simple app to display and update a greeting as the user types input. Add the following to src/index.js:

import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: ""
    };
  }

  render() {
    return (
      <Fragment>
        <h1>Hello {this.state.name}</h1>
        <input
          type="text"
          placeholder="Type your name..."
          onChange={e => this.setState({ name: e.target.value })}
        />
      </Fragment>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Run yarn start in the terminal, and you should see a header with a text input right below it rendered in the browser. If you copy and paste the code above into the Babel REPL, you can see how the code will be transpiled to vanilla JavaScript. Ok, so now what?

If we poke around in the file structure that create-react-app generated we will notice a file called package.json. This file is responsible for defining project dependencies and scripts such as start and build. Let’s go a level deeper. Type the following into the terminal:

git add .
git commit -m "initial commit"
yarn eject

When prompted, type y to complete the process. What did this do? Well, if we look at our directory structure, we will notice two new folders have been created: config and scripts. By running the eject command, we are removing our dependency on the magic of the create-react-app tool and getting a look under the hood at what’s really happening. Taking a look at package.json now, we can see that there are now many more dependencies listed than before, including Babel and Webpack. Under the config folder that was generated, we also see webpack.config.js and webpackDevServer.config.js. Take a few minutes to peek into these files and try to comprehend what they are doing.

Tying It All Together

React is an amazing framework for quickly creating stunning dynamic web apps, with a lot going on under the hood. JSX is an extension to JavaScript which allows us to write XML-like syntax to define DOM elements, which are translated by Babel into vanilla JS. Webpack is responsible for bundling all of our components together and running a local development server to test our code in the browser. I hope that this article has helped to demystify the magic of React, and bring about a deeper level of understanding.

Go here to view the code presented in this post.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

#reactjs #javascript #web-development

What is GEEK

Buddha Community

JSX, Babel and Webpack: The Magic Behind ReactJS
Tanya  Shields

Tanya Shields

1597755900

ReactJS | Understanding Babel and JSX

ReactJS : ReactJS is an open-source, component-based front-end library which is used only for building the user interfaces. React is flexible and declarative JavaScript Library. Due to slow speed of DOM ( Document Object Model ), React implements a Virtual DOM that is basically an abstraction of DOM. ReactJS also gives us a provision to write the JavaScript and HTML together.

Babel : Babel is a JavaScript compiler that transform the latest JavaScript features, which are not understandable to every browser, into a backward compatible version of JavaScript in current and older browsers or environments.

JSX : JSX is a syntactical extension to JavaScript. It comes with the full power of JavaScript. JSX produces React elements and can embed any JavaScript expression. Ultimately, the JSX is converted to JavaScript using compiler/transformers.


Setting up React and Babel

Get the React and ReactDOM scripts, place it with other scripts and remember to include it every time you use React or ReactDOM.

Now for Babel, create a folder structure say C:\react\work and move to it. We will now install the transpiler for working with Babel. Run the following commands :

npm install babel-cli

npm install babel-preset-react
npm install babel-plugin-transform-react-jsx

#reactjs #babel #html #jsx #javascript #programming

JSX, Babel and Webpack: The Magic Behind ReactJS

Creating an app in React is a true pleasure, especially coming from programming interactive apps in vanilla JavaScript. React utilizes an object oriented design pattern, with a couple of core concepts that are unique: first, there are components. A component in React is a class which represents an element (or set of elements) in the DOM, which have properties (or props) and can also carry state. State in a React component is reserved for properties that may change over time: the text input on a form, for example, or a button which toggles text displayed to the user. Components are typically separated into discrete files, following the convention ComponentName.js.

The second feature which is distinct to React is JSX. JSX — or JavaScript XML — is a syntax extension to standard JavaScript which allows us to incorporate XML-like syntax into our code. For example, with JSX we are allowed to write the following:

const greeting = <h1>Hello, World!</h1>

This is where things start to get interesting. If you are familiar with HTML, the above should look familiar. With standard JavaScript, however, something like the following would be required to achieve the same result:

const greeting = document.createElement("h1");
greeting.innerText = "Hello, World!";

How exactly does this work and why is it legal? As it turns out, JSX is actually transpiled into standard JavaScript behind the scenes. React uses a preprocessor called Babel to translate our code before it is rendered in the browser. If we head over to the Babel REPL, we can see exactly how our code will be converted:

const greeting = React.createElement("h1", null, "Hello, World!");

This should look familiar! The main difference here is that React uses its own copy of the DOM — the virtual DOM — in order to dynamically handle component loading and unloading (or mounting, in React terminology.)

So, how does React incorporate Babel? This is where Webpack comes in. Webpack is a package bundler for JavaScript that compiles modules into a single source, which is then rendered in the browser. As of ES6, JavaScript introduced the import and export keywords, allowing us to separate out our code into discrete modules and include dependencies. Remember the mention of components being split up into separate files? Webpack first determines the file hierarchy for the project and generates a dependency graph. From the dependency graph it compiles the code to a single source, using Babel to translate and remove the import and export statements, and convert JSX into standard JavaScript.

Let’s create a simple React app to tie all of these concepts together. In your terminal, navigate to your root development directory. Then type:

npx create-react-app my-app

The create-react-app tool does a few things for us, including running npm init and installing Babel and Webpack with some configuration scripts. Let’s move into our new project directory and remove all of the generated source files (as we will create our own from scratch):

cd my-app && rm src/*
touch src/index.js

We will next create a simple app to display and update a greeting as the user types input. Add the following to src/index.js:

import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: ""
    };
  }

  render() {
    return (
      <Fragment>
        <h1>Hello {this.state.name}</h1>
        <input
          type="text"
          placeholder="Type your name..."
          onChange={e => this.setState({ name: e.target.value })}
        />
      </Fragment>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Run yarn start in the terminal, and you should see a header with a text input right below it rendered in the browser. If you copy and paste the code above into the Babel REPL, you can see how the code will be transpiled to vanilla JavaScript. Ok, so now what?

If we poke around in the file structure that create-react-app generated we will notice a file called package.json. This file is responsible for defining project dependencies and scripts such as start and build. Let’s go a level deeper. Type the following into the terminal:

git add .
git commit -m "initial commit"
yarn eject

When prompted, type y to complete the process. What did this do? Well, if we look at our directory structure, we will notice two new folders have been created: config and scripts. By running the eject command, we are removing our dependency on the magic of the create-react-app tool and getting a look under the hood at what’s really happening. Taking a look at package.json now, we can see that there are now many more dependencies listed than before, including Babel and Webpack. Under the config folder that was generated, we also see webpack.config.js and webpackDevServer.config.js. Take a few minutes to peek into these files and try to comprehend what they are doing.

Tying It All Together

React is an amazing framework for quickly creating stunning dynamic web apps, with a lot going on under the hood. JSX is an extension to JavaScript which allows us to write XML-like syntax to define DOM elements, which are translated by Babel into vanilla JS. Webpack is responsible for bundling all of our components together and running a local development server to test our code in the browser. I hope that this article has helped to demystify the magic of React, and bring about a deeper level of understanding.

Go here to view the code presented in this post.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

#reactjs #javascript #web-development

Byte Cipher

1617110327

ReactJS Development Company USA | ReactJS Web Development Company

ByteCipher is one of the leading React JS app development Companies. We offer innovative, efficient and high performing app solutions. As a ReactJS web development company, ByteCipher is providing services for customized web app development, front end app development services, astonishing react to JS UI/UX development and designing solutions, reactJS app support and maintenance services, etc.

#reactjs development company usa #reactjs web development company #reactjs development company in india #reactjs development company india #reactjs development india

Dylan North

Dylan North

1583210830

How to set up the ReactJS environment with ES6, Webpack and Babel for Beginners

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.In this post, we’ll take a look at several different ways to set up a ReactJS environment, and get you set up using Facebook’s JavaScript Library.

Why ReactJS?

  1. ReactJS is very simple to implement because of its simple syntax and architecture as compared to the competitors.
  2. Component structure makes it easy to work on. A component-based structure is the future of the JavaScript framework. Even Google used the same for Angular 2.
  3. Virtual DOM concept of ReactJS makes it very efficient and fast.
  4. Because of VDOM, the page renders on the browser is a regular page which makes it good for SEO.
  5. It is open source and developed by Facebook.

Babel

Facebook keeps React up to date and even made it compatible with ES6. But as we know not all browsers support all the properties of ES6. So we use Babel for this purpose. Babel compiles the ES6 code into ES5 code so that it can run in the old browser.

Webpack

Webpack is a module bundler. It manages static assets and minifies and compiles files like SaaS, Less, and Typescript.

Webpack checks for import and require statement in files and builds a dependency graph.

What and how webpack will work is determined by webpack.config.js.

First, we have to make sure NodeJS and NPM are installed. Using npm we will install all the packages we need.

First, we will create a package.json file to save all the dependencies we need. Type this command in the terminal and enter the details it asks.

Now, let’s install react and react DOM.

npm install --save react@0.14.7

npm install --save react-dom@0.14.7

Next, we will need webpack and webpack development server. To install this, type this command in the terminal.

npm install --save-dev webpack@1.12.12

npm install webpack-dev-server@1.12.1 –g

Now as the bundling tool is installed we need our ES6 transpiler i.e. Babel. To install, type these command in the terminal:

npm install --save-dev babel-loader@6.2.1
npm install --save-dev babel-core@6.4.5
npm install --save-dev babel-preset-es2015@6.3.13
npm install --save-dev babel-preset-react@6.3.13

Babel loader is for minifying and compiling files while presets ES2015 are for different plugins like arrow function, classes, and duplicate keys.

Now create a file helloWorld.js and add this code:

var react = require('react');

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

var helloWorld = react.createClass(function(){

render:function(){

            return(

            <div>Hello World</div>

);

   }

});

ReactDOM.render(

 < helloWorld />,

 document.getElementById('hello')

);

Create another file content.js in the same directory and add this code:

var react = require('react');
var  ReactDOM = require('react-dom');
var content= react.createClass(function(){
render:function(){
            return(
            <div>This is content</div>
);
}
});
ReactDOM.render(
  < content />,
  document.getElementById(' content ')
);

In the same directory now create another file main.js where we will import these two files:

var helloWorld =  require('./ helloWorld ');
var content =  require('./ content ');

Create index.js file with the following content:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello React</title>
  </head>
  <body>
    <div id="hello"></div>
    <div id="content"></div>
  </body>
</html>

Configuring webpack

Now as we know the webpack is a module bundler and can bundle multiple module files into one. Let’s create a webpack.config.js file and add the following config.

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
  {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
    }
  }
]
  },
};

Let’s see what happened with the configuration file. First, we imported the path and webpack. Require will search for the webpack module everywhere and it will import it from there.

Entry will be the file where we are importing all js and adding routing while output will be the compiled file. The loader is used to minify and compile files. Here we are using only the Babel loader, so we defined only that. We can also add other loaders according to the dependencies.

Finally, we need to link this file to the main index file.

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello React</title>
  </head>
  <body>
    <div id="hello"></div>
    <div id="content"></div>
    <script src="bundle.js"></script>
  </body>
</html>

Now open the terminal and run the webpack server by typing this:

webpack-dev-server --progress –colors

What Next?

Now that our environment is setup you can check the official documentation to learn more about ReactJS.

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.

Thanks for reading !

#react #reactjs #es6 #javascript #Webpack

Billy Chandler

Billy Chandler

1559923246

Setting up Reactjs using Webpack 4 and Babel 7

In this tutorial we will be setting up our very own reactjs from scratch using webpack and babel, so grab your pen and paper lets spin the learning wheel.

Almost everyone who started out to learn reactjs was introduced to create-react-app, which is an awesome way to bootstrap any reactjs project. We were happy with it since you can just run a simple command, then boom your reactjs app development is ready. But at some point in your career you’d want to configure everything from scratch to fit a particular purpose.

Table of Contents

  • Setting up the Project
  • Setting up Webpack
  • Setting up Babel
  • Setting up React
  • Connecting React Component to the DOM
  • Finishing Touches
  • Conclusion

Setting up the Project

Before you can get started, you should make sure to have an installed editor and terminal on your machine. In addition, you will need an installed version of node with npm. Make sure to have setup everything of it before you continue to read.

Before we start writing any code, lets create a new directory where our project will stay. In any location on your computer, run the following in your terminal

mkdir webpack-babel-react-starter
cd webpack-babel-react-starter

We need to initialise our project with a package.json file, since we are going to install some packages that is vital for the setup. Simply run yarn init -y

For this tutorial i will be making use of yarn as my package manager, if you are using npm, make sure you run the corresponding command, it should work as expected.

Setting up Webpack

Webpack is one of the most popular bundler out there. It internally builds a dependency graph when it processes your application, this graph maps every module your project needs and generates one or more bundles. Since version 4.0.0, webpack does not require a configuration file to bundle your project, nevertheless it is incredibly configurable to better fit your needs.

let’s install it by running:

yarn add webpack --dev

We also need to install the webpack cli

yarn add webpack-cli --dev

After installing this two packages, you will notice a new addition in our project, the node_modules and devDependencies section in our package.json file. Next thing to do is to add the webpack you just install into the package.json file.

"scripts": {
  "build": "webpack --mode production"
}

At this point you don’t really need a configuration file to get started, which is a cool addition to webpack 4

Setting up Babel

Modern javascript is written in ES6 or ES7, but not every browser understands this modern javascript, it’s at this juncture we need babel to do the heavy lighting for us. Babel is a tool-chain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Checkout there docs for more info about what they can do for you.

React components are mostly written in ES6, with the concept of imports, class and other ES6+ features, which older browsers do not understand. Webpack on it’s own does not know how to transform or better still transpile the ES6 code to ES5 code. But their is hope for us, webpack have this concept of loaders, a webpack loader takes something as the input and produces something else as the output.

For our setup, we will use babel-loader which is webpack loader that will transpile our ES6 code for us. Before we start using babel-loader, we need to install some packages and setup babel preset env which will target the particular javascript version we want to transpile to.

let’s install all the dependencies:

yarn add @babel/core @babel/preset-env @babel/preset-react babel-loader --dev

We also need to setup our babel config file, create a new file in the root directory called .babelrc and write the following configuration to it

{
  "presets": ["@babel/env", "@babel/react"]
}

The above configuration will ensure that babel transpiles our react code, which is JSX and any other ES6+ code we have to ES5 code.

Now is the perfect time to create a minimal webpack configuration for our project. Create a webpack.config.js file in the root directory and write the following configuration for it

module.exports = {
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
}

What the above configuration does is that for every file with a js or jsx extension, excluding the node_modules folder and it’s content, webpack uses babel-loader to transpile the ES6 code to ES5. With this done, lets head over to writing our react component.

Setting up React

We will be creating a very simple react component, that renders a text and a button, but in order to make use of react we need to install some dependencies, react and react-dom .

yarn add react react-dom

After installing those, create a new folder in the root directory, let’s call it src inside it create index.js file

In the index.js file write the following code:

import React from "react";
import ReactDOM from "react-dom";

const Index = () => {
  return (
    
      
        
          React Page {" "}
        
        

        <a
          className="button-line"
          href="https://github.com/deityhub"
          target="_blank"
        >
          Know more
        
      
    
  );
};

export default Index;

It’s time to test things out and see how powerful webpack is. Open up your terminal once again and run

yarn run build

If it’s successful you should see a dist folder created for us by webpack, and inside it is an index.js file which have minified version of our ES5 code. Why is the code minified, if you remember in our build script in package.json we specified a --mode production flag after the webpack command, under the hood, webpack will generate a minified version of our ES5 code. To see a readable format of the transpiled code, you can swap the --mode production with --mode development

Yay!, the output was great but that’s not what we really want for our react app, we want our transpiled code to be visible in our browser. So let’s setup html and also css(scss) to work with our webpack.

Connecting React Component to the DOM

We need to setup an html file so that our react component can be rendered on the dom, but we can’t just create a random html file and hook up our react to it using react dom. So to achieve this we need to install the package html-webpack-plugin

yarn add html-webpack-plugin --dev

Adjust your webpack.config.js file to look like this

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    })
  ]
};

If you notice, we are adjusting the input and output so we have a bit more control over the naming and target of our files.

Nextup is to create an html file inside src folder, let’s call it index.html and then paste the following code into it



  
    
    
    React, Webpack, Babel Starter Pack
    
  
  
     You need to enable JavaScript to run this app. 
    
    

  

Since we are in the src let’s make some adjustments to our react component, first we create a new folder components then inside this folder a two files app.js and app.scss then make this following adjustments to our code:

In ./src/index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/app";

ReactDOM.render(, document.getElementById("app"));

In ./src/components/app.js

import React from "react";
import "./app.scss";

const App = () => {
  return (
    
      
        
          React Page {" "}
        
        

        <a
          className="button-line"
          href="https://github.com/deityhub"
          target="_blank"
        >
          Know more now
        
      
    
  );
};

export default App;

In ./src/components/app.scss

body {
  background: linear-gradient(253deg, #0cc898, #1797d2, #864fe1);
  background-size: 300% 300%;
  -webkit-animation: Background 25s ease infinite;
  -moz-animation: Background 25s ease infinite;
  animation: Background 25s ease infinite;
}

.full-screen {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
//you need to setup file-loader in webpack before you can use images
  background: url("../../assests/image/background.png");
  background-size: cover;
  background-position: center;
  width: 100%;
  height: 100%;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  //_ works with row or column_

  flex-direction: column;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
  text-align: center;
}

h1 {
  color: #fff;
  font-family: "Open Sans", sans-serif;
  font-weight: 800;
  font-size: 4em;
  letter-spacing: -2px;
  text-align: center;
  text-shadow: 1px 2px 1px rgba(0, 0, 0, 0.6);

  &:after {
    display: block;
    color: #fff;
    letter-spacing: 1px;
    font-family: "Poiret One", sans-serif;
    content: "React project powered by webpack and babel with support for sass";
    font-size: 0.4em;
    text-align: center;
  }
}

.button-line {
  font-family: "Open Sans", sans-serif;
  text-transform: uppercase;
  letter-spacing: 2px;
  background: transparent;
  border: 1px solid #fff;
  color: #fff;
  text-align: center;
  font-size: 1.4em;
  opacity: 0.8;
  padding: 20px 40px;
  text-decoration: none;
  transition: all 0.5s ease;
  margin: 0 auto;
  display: block;

  &:hover {
    opacity: 1;
    background-color: #fff;
    color: grey;
  }
}

@-webkit-keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@-moz-keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

We will be adding some styling in addition to the html and react component that we will render in the dom. So before we run our code to test it, we need to configure our webpack so it will know how to handle any .css or .scss file being passed through it.

yarn add css-loader sass-loader mini-css-extract-plugin node-sass --dev

sass-loader being installed here is used by webpack to convert our .scss to a .css file that the browser understands, and under the hood it makes use of node-sass to achieve this. Then mini-css-extract-plugin as the name suggests, abstract all our css files into a single css file, instead of the normal behaviour that webpack offers, which is to bundle your css file with the final .js output file which then injects the css into your rendered html output when you run the code.

Open up your webpack config file and adjust your code to look like this

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /.(css|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};

There is a point to note here, the order of your loaders in the webpack config file matters a lot, because webpack processes the loaders from right to left. So using the test for css files for example, it will run sass-loader first, then css-loader and finally MiniCssExtractPlugin.

There is one more thing to do, let’s install webpack dev server, this will create a development server for us and monitor our files for any changes during development.

yarn add webpack-dev-server --dev

Then open your package.json file and make the following adjustments in your scripts tag

"scripts": {
    "start": "webpack --mode development",
    "dev": "webpack-dev-server --mode development --open",
    "build": "webpack --mode production"
  }

That’s to much code right?, so let’s test our code by running yarn run dev

Setting up Reactjs using Webpack 4 and Babel 7 if everything went well, you should see something like this on your browser.

Setting up Reactjs using Webpack 4 and Babel 7

Finishing Touches

If you followed this tutorial step by step, I’m quite confident that you will end up knowing and mastering the usage of webpack and babel. Going forward i want us to add two more features to this project, just to demonstrate that you can extend or add more features tomorrow when working on a more advanced react project than this.

Open your terminal and install this packages

yarn add file-loader @babel/plugin-proposal-class-properties --dev

file-loader will handle all the scenario where we want to import an image or an svg or even a gif while @babel/plugin-proposal-class-properties will handle react class components and static class properties.

In webpack.config.js adjust it to look like this

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /.(css|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      },
      {
        test: /.(jpg|jpeg|png|gif|mp3|svg)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[path][name]-[hash:8].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};

In .babelrc file, also adjust it to look like this

{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Finally run yarn run dev to make sure everything is stile working.

Conclusion

If you made it thus far, congratulation you deserve a pizza, because not everybody that started out to learn something new eventually completes it. I want you to work on what you’ve learnt in this tutorial, extend the configuration and build something awesome from it. You can checkout the github link to the complete code.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

#reactjs #webpack #javascript #css #sass