Setting A React Project From Scratch Using Babel And Webpack

Setting A React Project From Scratch Using Babel And Webpack

This guide will show how can we set up own react project using babel and webpack. We would configure webpack to use babel to compile the jsx to js and run a development server for serving the compiled files.

This guide will show how can we set up own react project using babel and webpack. We would configure webpack to use babel to compile the jsx to js and run a development server for serving the compiled files.

There are many tools for getting a boilerplate code generated available for reactjs. The most popular tool used by many developers is create-react-app, which comes with many configuration options.

Content

  • Introduction to babel and webpack
  • Configuring webpack
  • Using babel with webpack
  • Using css and file loader with webpack
  • Using webpack dev server

Introduction

This guide will show how can we set up own react project using babel and webpack. We would configure webpack to use babel to compile the jsx to js and run a development server for serving the compiled files.

Webpack

Webpack is used to compile JavaScript modules. Once installed, you can interface with webpack either from its CLI or API. If you’re still new to webpack, please read through the core concepts and this comparison to learn why you might use it over the other tools that are out in the community.

Webpack takes all our dependencies and converts to static resources so that it can be served to the client. The bundling is very important because most browsers limit the number of the request for resources to 6 or 7 requests. Bundling helps us to avoid sending unnecessary modules as a bonus. Webpack uses an internal cache to load the module only once and the precious bandwidth is saved resulting in faster loading time.

Babel

Webpack is used to compile JavaScript modules. Once installed, you can interface with webpack either from its CLI or API. If you’re still new to webpack, please read through the core concepts and this comparison to learn why you might use it over the other tools that are out in the community.

Babbel is used to convert the jsx to js. JSX is short form javascript XML syntax, it provides us with an easy way for writing react code.

<pre name="a32b" id="a32b" class="graf graf--pre graf-after--p">import React from "react";</pre>

<pre name="5289" id="5289" class="graf graf--pre graf-after--pre">function App(props){
 return(
  <div>
     <b>Hello world!</b>
   </div>
 )
}</pre>

With the use of jsx, it is easy to read and write react code. Here is the sample of code without jsx.

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function App(props) {
  return _react2.default.createElement(
    "div",
    null,
    _react2.default.createElement(
      "b",
      null,
      "Hello world!"
    )
  );
}

exports.default = App;

It is very difficult to read this code and it is more error-prone whereas jsx provides us nice HTML like syntax.

Requirements

To set our project we would require these npm modules

  • Introduction to babel and webpack
  • Configuring webpack
  • Using babel with webpack
  • Using css and file loader with webpack
  • Using webpack dev server

We can use npm or yarn to install these dependencies

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader css-loader webpack webpack-cli style-loader webpack-dev-server

The root of the project contains an src folder with index.js as entry file.

The folder componentscontains all the component for the project and dist folder all the code that is compiled.

Use Bit to build faster with components

Bit turns your components into building blocks your team can easily share, organize and use across all your apps and projects in full sync. Try it out.

Let us configure the webpacks

The webpacks are an extremely configurable piece of software we can pass arguments to cli command or create a configuration file named webpack.config.js . We should export an object with configuration property.

{
entry: "./src/index.js",
mode: "development",
output: {
    filename: "./main.js"
  },
}

The entry specify the root of the source code of the project. The mode specify the type of environment for the compilation tells where the compiled file should be placed.

Creating Our Sample Project

Our project has an index.html in dist folder and the structure of the HTML is

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>React From Scratch</title>
  </head>
  <body>
    <div id="root">
    </div>
  </body>
  <script type="text/javascript" src="/main.js">

</script>
</html>

The HTML contains the script tag pointing to our main compiled file and when the file is compiled it is included in the HTML. Then we should install react and react-dom packages.

npm install react react-dom

Now index.js which is standard react rendering the file.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import App from "./component/app.component";

ReactDOM.render(<App />, document.querySelector("#root"));
app.component.js
import React, { Component } from "react";
import s from "./app.component.css";
class MyComponent extends Component {
  render() {
    return <div className={s.intro}>Hello World</div>;
  }
}

export default MyComponent;
app.component.css
.intro {
  background-color: yellow;
}

Configuring the babel

Babel is configured using the presets which can be used to transpile almost any web technology including less to css, jsx to js, typescript to js many more. We would only use two preset react and env . We can configure babel using cli, file or package.json file, we would use package.json for configuration. Preset are like modules which help to transpile one language to other.

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

We would add these lines to the package.json file, it would let the babel know that these preset should be used for transpile. Now we should configure webpack to use babel.

Configuring WebPack for Babel And Other Loaders

Now we would use babel-loader for using babel with webpack and webpack provide us hooks to process the files before it is processed and these are called module and are easy to configure.

Using JS files

module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader"
        }
      },
    ]
}

The rules are array used to specifying what should be done when this type of file is encountered. The key testspecifies the regex for the file, we use it to select all the files with extension .m and .js and exclude the folder node_module and bower_components because we don’t what to transpile the node_module files then we specify the babel-loader to be used.Now our javascript files will be compiled by babel then processed by the webpack.

Using CSS files

module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true
            }
          }
        ]
      },
   ]
}

We would use style-loader and css-loader for this task. The use key can also take an array of the objects or string. The loaders are run from last to first, therefore our file will first go to css-loader, we have specified the option of using modules, which make our css exclusive to the only component in which it is imported. The css-loader would resolve all the import in the css files and then the style-loader would add these in the form of style tag in the head.

<style>
<-- your css -->
</style>

Using Static assets

module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true
            }
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ["file-loader"]
      }
    ]
  }

If we encounter png, svg, jpg or gif file we would use file-loader for handling these files. It is very important to handle these file carefully and optimize files loading mechanism.

Running dev server

devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    port: 9000,
    watchContentBase: true,
    progress: true
  },

The module provides us with a very easy and configurable method of running our development server. contentBase the entry point for our compiled resources which is index.html port tells on which port the server is listening. watchContentBase is very interesting, it tells the server to watch for the changes in the files directory in the contentBase folder.

const path = require("path");

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  output: {
    filename: "./main.js"
  },
  devServer: {
    contentBase: path.join(__dirname, "dist"),
    compress: true,
    port: 9000,
    watchContentBase: true,
    progress: true
  },

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              modules: true
            }
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ["file-loader"]
      }
    ]
  }
};

Let start are server using package.json file.

"scripts": {
    "dev": "webpack-dev-server",
    "start": "webpack"
  },

We can now run npm run dev for starting our web server.

Conclusion

This is just an overview of how we can configure webpack and babel for reactjs. This is just a tip of the iceberg, you can configure this to use less instead of css or typescript instead of the js, minify the css files etc.

  • Introduction to babel and webpack
  • Configuring webpack
  • Using babel with webpack
  • Using css and file loader with webpack
  • Using webpack dev server

Learn More

Modern React with Redux

Become a JavaScript developer - Learn (React, Node,Angular)

The Complete React Web Developer Course (2nd Edition)

Node with React: Fullstack Web Development

Beginner Full Stack Web Development: HTML, CSS, React & Node

React JS and Redux - Mastering Web Apps

React 16 - The Complete Guide (incl. React Router 4 & Redux)

MERN Stack Front To Back: Full Stack React, Redux & Node.js

URLs and Webpack in Reactjs

URLs and Webpack in Reactjs

URLs and Webpack in Reactjs - I am still a newbie in ReactJS. I've been following series of tutorials and articles on the framework and decided to start putting what I've learnt so far into practice.

My website, dillionmegida.com was built with PHP. You could check it out as I highly appreciate reviews. I'm though aspiring to be a full-stack javascript developer so I'm in some way trying to depart from PHP :)

I decided to replicate my homepage using React and to broaden my skills in using components.

It was going quite successful until I tried using an <img> JSX element. I used it like;

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src='../img/deee.jpeg' alt='My profile picture'/>
    </div>
)
export default Profilepic;

The img folder was a sub-directory of the src folder.

My aim here was to have my profile picture as a component with some styling to be used on my homepage and any other desired page. The src for the img tag was not been used appropriately as my image was not displayed.

I paused to think of the problem, inspected my page and discovered the src displayed there was exactly as I inputted it. So silly of me :( I made some researches which helped me remember that most attributes of JSX element are not as mostly used with HTML, but have to be enclosed in curly braces.

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={'../img/deee.jpeg'} alt='My profile picture'/>
    </div>
)
export default Profilepic;

I tried rendering the page again and my image was still not displayed.

Funny enough, I quickly thought of a trick (for the first time);

...
import Dp from '../img/deee.jpeg'
...
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={Dp} alt='My profile picture'/>
    </div>
)

To my amazement, it worked. I was excited and at the same time sad, with feeling of little guilt. I didn't know why. lol. I said to myself, 'I am not doing the right thing :(' and also asked myself, 'Is react as crazy as this?'

I headed back to google to make some more research and got to discover that the webpack that React (create-react-app) automatically installed had been configured to use the public folder (at the same level with src folder) for relative URLs (such as my image URL).

Using ...<img src={'../img/deee.jpeg'} />..., React was actually checking the public folder for the image sub-directory which it couldn't find.

Solution

1. Change the location of the image folder

I changed the location of the image folder making it a sub-directory under the public directory and it worked as expected.

2. Use the require keyword

Just as the import keyword is used for relative URLs, the require keyword does same. So, I was able to do this;

import React from 'react'
 
let dpStyle = {
    // Some styles
}
 
let Profilepic = () => (
    <div className={dpStyle}>
        <img src={require('../img/deee.jpeg')} alt='My profile picture'/>
    </div>
)
export default Profilepic;

and in the other pages where the Profilepic component was required and used, my image displayed perfectly. :D

Like I said, I am still a newbie at ReactJS but I hope this little experience would be helpful for you too. There are other super powers of webpacks too which I would still be learning. Please do share in the comment section corrections on this article and also helpful Tips.

I'll be documenting my experience in my ReactJS journey as much as I can. Stay tuned and thanks for reading.

Originally published by Megida Dillion at dillion.hashnode.dev

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development


Learn ReactJS with Webpack 4, Babel 7, and Material Design

Learn ReactJS with Webpack 4, Babel 7, and Material Design

Quick and simple, fast guide on integrating ReactJS with Webpack, Babel and Material Design. This is a short tutorial which will get your ReactJS app running with Webpack and Babel.

Quick and simple, fast guide on integrating ReactJS with Webpack, Babel and Material Design. This is a short tutorial which will get your ReactJS app running with Webpack and Babel.

**React **is a JavaScript library for building user interfaces and it has three main characteristics:

  • Declarative
  • Component-Based
  • Learn Once, Write Anywhere

**Webpack **is an open source JavaScript module bundler. Its main purpose is to bundle **JavaScript **files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. **Webpack **takes modules with dependencies and generates static assets representing those modules.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of **JavaScript **in current and older browsers or environments. Here are the main things **Babel **can do for you:

  • Declarative
  • Component-Based
  • Learn Once, Write Anywhere

Setting up Reactjs using Webpack 4 and Babel 7

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.

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

if everything went well, you should see something like this on your browser.

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