How to use ReactJS with Webpack 4, Babel 7, and Material Design

Hire Reactjs Developers

This tutorial is about how to use React with Webpack 4 and Babel 7, and by the end of this tutorial, you will be able to add Material Dashboard React on top of a newly built application. 

Prerequisites:

Before starting, you will need to have the latest version of Nodejs and npm installed on your machine. 

Step-by-Step Guide to Use ReactJS with Webpack 4, Babel 7, and Material Design 

  • Create a New Project Folder with package.json

The first step is to create a new folder for our new app and enter it:

mkdir react-webpack-babel-tutorial
cd react-webpack-babel-tutorial

After creating the folder where we will develop the app, we will add a package.json file to1 it. That is usually done in two different ways, and you can opt for one of them. 

  • Create package.json file without any configuration 

npm init -y

The package.json file is created with some information in it. 

Reactjs Development

Source

Hire Reactjs

Source 

We will be adding an index.html and index.js files to our new project folder (inside an src folder). 

  • Linux/macOS Commands

mkdir src
touch src/index.html
touch src/index.js

  • Windows Commands

mkdir src
echo “” > src\index.html
echo “” > src\index.js

Add the following template inside the index.html

<!DOCTYPE html><html lang=”en”>  <head>    <meta charset=”utf-8″>    <meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no”>    <meta name=”theme-color” content=”#000000″>    <title>React Tutorial</title>  </head>  <body>    <noscript>      You need to enable JavaScript to run this app.    </noscript>    <div id=”root”></div>    <!–      This HTML file is a template.      If you open it directly in the browser, you will see an empty page.      You can add webfonts, meta tags, or analytics to this file.      The build step will place the bundled scripts into the <body> tag.    –>  </body></html>

Now, try adding some text inside the index.js to see how it appears: 

(function () {  console.log(“hey mister”); }());

Reactjs Development

Source 

  • Adding Webpack 

This step will add all the ‘Webpack’ packages that we need in the project. Further, we will install them as devDependencies as we will use them in the development mode. 

npm install –save-dev webpack webpack-cli webpack-dev-server

  • Webpack 

Required for the configuration of the new app

  • Webpack-cli

It is used so that we can use Webpack in the command line easily.  

  • Webpack-dev-server

It is used to automatically refresh the page when we make changes in the file of our new app. It is a server that works without stopping. 

Reactjs Development

Source 

This command will add dependencies automatically in the package.json file under the devDependencies object. eg:

“devDependencies”: {
“webpack”: “^4.19.0”, 
“webpack-cli”: “^3.1.0”,
“webpack-dev-server”: “^3.1.8”

}

The installation of these plugins will make some changes in the project folder. Package-lock.json and node_modules are added. 

Reactjs developers

Source 

In this step, we will add a new file to our project, the config file for Webpack, named webpack.config.js. 

  1. macOS/Linux Command

touch webpack.config.js

  1. Windows Command

echo “” > webpack.config.js

Let’s suppose you don’t want to create a new file. In that case, you can manually create it. Now, we will work with some paths inside the Webpack config file. First, we will install a path in our project as a devDependency. 

npm install –save-dev path

Add a plugin called html-webpack-plugin, which will help you inject the index.js inside the HTML file without needing any manual help. 

npm install –save-dev html-webpack-plugin

Edit your package.json and delete all he ^ caret occurrences. 

In the package.json, we will add new scripts inside the scripts object after the test script.

“webpack”: “webpack”,”start”: “webpack-dev-server –open”

Once done, your package.json will look like this:

{  “name”: “react-webpack-babel-tutorial”,  “version”: “1.0.0”,  “description”: “This is a Tutorial to showcase the usage of React with Webpack and Babel”,  “main”: “index.js”,  “scripts”: {    “test”: “echo \”Error: no test specified\” && exit 1″,    “webpack”: “webpack”,    “start”: “webpack-dev-server –open”  },  “repository”: {    “type”: “git”,    “url”: “git+https://github.com/creativetimofficial/react-webpack-babel-tutorial.git”  },  “keywords”: [    “react”,    “webpack”,    “babel”,    “creative-tim”,    “material-design”  ],  “author”: “Creative Tim &lt;[email protected]> (https://www.creative-tim.com/)”,  “license”: “MIT”,  “bugs”: {    “url”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial/issues”  },  “homepage”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial#readme”,  “devDependencies”: {    “html-webpack-plugin”: “3.2.0”,    “path”: “0.12.7”,    “webpack”: “4.19.0”,    “webpack-cli”: “3.1.0”,    “webpack-dev-server”: “3.1.8”  }}

Now, we will run these commands one by one to see how it appears:

npm run webpack

Webpack will automatically take the src/index.js file. Then, it will compile this file and output it inside dist/main.js before minifying the code. Remember that we still haven’t configured the ‘Webpack config’ file, so some warning might appear on the screen. 

Reactjs Developers

Source 

Reactjs Development Services

Source 

If we run another command, Npm start, we will notice that webpack-dev-server has automatically started a server and opened the default browser using this server. 

Again, we don’t have our webpack.config.js configured, so the output we are trying to see will not appear. So, there might appear some warnings. 

Reactjs

Source 

Now, we will add the given template to our Webpack config file. 

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: ‘index.bundle.js’  },  mode: process.env.NODE_ENV || ‘development’,  resolve: {    modules: [path.resolve(__dirname, ‘src’), ‘node_modules’]  },  devServer: {    contentBase: path.join(__dirname,’src’)  },  plugins: [    new HtmlWebpackPlugin({      template: path.join(__dirname,’src’,’index.html’)    })  ]};

  1. Entry and output 

Using this, we can tell our server what exactly has to be compiled and from where.

(entry: path.join(__dirname,’src’,’index.js’),)

You can also see where the output version will go. 

  1. Mode

This is about the mode of our output, which we will set up for development. In case we have specified the NODE_ENV variable, it will use that one then. 

“webpack”: “NODE_ENV=production webpack”,

  1. Resolve 

Used to import anything from the src folder in relative paths and not from the absolute ones. That’s similar to node_modules, which imports anything from node_modules directly without absolute paths. 

  1. devServer

This lets the webpack-dev-server know what files are to be served. Everything from our src folder has to be served in the browser. 

  1. Plugins 

Now we will decide which plugins are required in the app. First, we need html-webpack-plugin that signals the server that index.bundle.js must be injected into the index.html file. 

Run the ‘npm run webpack’ command to see the differences. 

Reactjs

Source 

Reactjs Services

Source 

You can see that now we have changed the output from the dist folder to the build folder. That means we have changed the mode of Webpack, and now the code will look different. 

Hire Reactjs Developers

Source 

Reactjs Development

Source 

Reactjs Apps

Source 

Now everything that was in the src folder will be shifted to webpack-dev-server. Now is the time to add React and Babel. 

  • Add React and ReactDOM to our project as normal dependencies.

npm install –save react react-dom

So, if now we want to add React code inside our JS file, Webpack will show us an error. 

We will now modify the index.js file:

import React from “react”;import ReactDOM from “react-dom”;let HelloWorld = () => {  return <h1>Hello there World!</h1>}ReactDOM.render(  <HelloWorld/>,  document.getElementById(“root”));

Now run command – npm start 

Reactjs development

Source 

Hire Reactjs Developers

Source 

Babel will now signal Webpack how to compile React code. Now we will add a bunch of Babel packages to our app as devDependencies. 

npm install –save-dev @babel/core @babel/node @babel/preset-env @babel/preset-react babel-loader

  1. @babel/core

 Used when ES6 is compiled into ES5

  1. @babel/node

Used to import our plugins and packages inside the webpack.config.js instead of ‘require’ them. 

  1. @babel/preset-env

It will determine which plugins or transformations should be used based on the browser matrix you want to support. 

  1. @babel/preset-react

It compiles the React code into ES5 code.

  • @babel-loader 

Webpack helper that transforms JavaScript dependencies with Babel. 

We will add a loader that will help us import and use CSS files and SCSS files. 

npm install –save-dev style-loader css-loader sass-loader node-sass

  • style-loader

Helps you add to the DOM the styles you want in the app. 

  • css-loader

Import CSS files into the project 

  • sass-loader

Import SCSS files into our project 

  • node-sass

Compile SCSS files into normal CSS files. 

Now, we will create a new CSS file and add it to our folders:

  1. macOS/Linux command 

touch src/index.scss

  1. Windows command 

echo “” > src/index.scss

Also we will add some styles to it:

body {  div#root{    background-color: #222;    color: #8EE4AF;  }}

We will also change index.js by adding an import for the SCSS file. 

         import React from “react”;import ReactDOM from “react-dom”;

        // this line is new// we now have some nice styles on our react appimport “index.scss”;

         let HelloWorld = () => {  return <h1>Hello there World!</h1>}

         ReactDOM.render(  <HelloWorld/>,  document.getElementById(“root”));

Delete the carets from package.json and after that the package.json file must do like this:

{  “name”: “react-webpack-babel-tutorial”,  “version”: “1.0.0”,  “description”: “This is a Tutorial to showcase the usage of React with Webpack and Babel”,  “main”: “index.js”,  “scripts”: {    “test”: “echo \”Error: no test specified\” && exit 1″,    “webpack”: “webpack”,    “start”: “webpack-dev-server –open”  },  “repository”: {    “type”: “git”,    “url”: “git+https://github.com/creativetimofficial/react-webpack-babel-tutorial.git”  },  “keywords”: [    “react”,    “webpack”,    “babel”,    “creative-tim”,    “material-design”  ],  “author”: “Creative Tim &lt;[email protected]> (https://www.creative-tim.com/)”,  “license”: “MIT”,  “bugs”: {    “url”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial/issues”  },  “homepage”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial#readme”,  “devDependencies”: {    “@babel/core”: “7.0.1”,    “@babel/node”: “7.0.0”,    “@babel/preset-env”: “7.0.0”,    “@babel/preset-react”: “7.0.0”,    “babel-loader”: “8.0.2”,    “css-loader”: “1.0.0”,    “html-webpack-plugin”: “3.2.0”,    “node-sass”: “4.9.3”,    “path”: “0.12.7”,    “sass-loader”: “7.1.0”,    “style-loader”: “0.23.0”,    “webpack”: “4.19.0”,    “webpack-cli”: “3.1.0”,    “webpack-dev-server”: “3.1.8”  },  “dependencies”: {    “react”: “16.5.1”,    “react-dom”: “16.5.1”  }}

Now we will tell Webpack that it should use Babel and the style loaders to compile SCSS code and React. After this, we will add a configuration file for Babel, for which we need to create a file called .babelrc, which will help us configure Babel. 

Run in command line the following:

  1. macOS/Linux Command

touch .babelrc

  1. Windows Command

echo “” > .babelrc

Now, we will add the code inside .babelrc so that the babel-loader knows how to compile the code. 

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

Now, we will import all files in the project along with a plugin that helps us work with classes. We will also add class properties in our classes. 

npm install –save-dev file-loader @babel/plugin-proposal-class-properties

Now, we need to make changes inside webpack.config.js so that Webpack now uses Babel. Besides, we will also configure Webpack to listen for style files. Finally, we will also change ‘require’ statements to import ones. 

// old// const path = require(‘path’);// const HtmlWebpackPlugin = require(‘html-webpack-plugin’);// newimport path from ‘path’;import HtmlWebpackPlugin from ‘html-webpack-plugin’;module.exports = {  entry: path.join(__dirname,’src’,’index.js’),  output: {    path: path.join(__dirname,’build’),    filename: ‘index.bundle.js’  },  mode: process.env.NODE_ENV || ‘development’,  resolve: {    modules: [path.resolve(__dirname, ‘src’), ‘node_modules’]  },  devServer: {    contentBase: path.join(__dirname,’src’)  },  module: {    rules: [      {        // this is so that we can compile any React,        // ES6 and above into normal ES5 syntax        test: /\.(js|jsx)$/,        // we do not want anything from node_modules to be compiled        exclude: /node_modules/,        use: [‘babel-loader’]      },      {        test: /\.(css|scss)$/,        use: [          “style-loader”, // creates style nodes from JS strings          “css-loader”, // translates CSS into CommonJS          “sass-loader” // compiles Sass to CSS, using Node Sass by default        ]      },      {        test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,        loaders: [‘file-loader’]      }    ]  },  plugins: [    new HtmlWebpackPlugin({      template: path.join(__dirname,’src’,’index.html’)    })  ]};

Also, we need to tell the scripts that we use to import and not require statements inside the config files of Webpack. 

{  “name”: “react-webpack-babel-tutorial”,  “version”: “1.0.0”,  “description”: “This is a Tutorial to showcase the usage of React with Webpack and Babel”,  “main”: “index.js”,  “scripts”: {    “test”: “echo \”Error: no test specified\” && exit 1″,    “webpack”: “babel-node ./node_modules/webpack/bin/webpack”,    “start”: “babel-node ./node_modules/webpack-dev-server/bin/webpack-dev-server –open”  },  “repository”: {    “type”: “git”,    “url”: “git+https://github.com/creativetimofficial/react-webpack-babel-tutorial.git”  },  “keywords”: [    “react”,    “webpack”,    “babel”,    “creative-tim”,    “material-design”  ],  “author”: “Creative Tim <[email protected]> (https://www.creative-tim.com/)”,  “license”: “MIT”,  “bugs”: {    “url”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial/issues”  },  “homepage”: “https://github.com/creativetimofficial/react-webpack-babel-tutorial#readme”,  “devDependencies”: {    “@babel/core”: “7.0.1”,    “@babel/node”: “7.0.0”,    “@babel/plugin-proposal-class-properties”: “7.0.0”,    “@babel/preset-env”: “7.0.0”,    “@babel/preset-react”: “7.0.0”,    “babel-loader”: “8.0.2”,    “css-loader”: “1.0.0”,    “file-loader”: “2.0.0”,    “html-webpack-plugin”: “3.2.0”,    “node-sass”: “4.9.3”,    “path”: “0.12.7”,    “sass-loader”: “7.1.0”,    “style-loader”: “0.23.0”,    “webpack”: “4.19.0”,    “webpack-cli”: “3.1.0”,    “webpack-dev-server”: “3.1.8”  },  “dependencies”: {    “react”: “16.5.1”,    “react-dom”: “16.5.1”  }}

We need to add one more thing here @babel/plugin-proposal-class-properties to .babelrc file. After that, Babel will deal with class properties:

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

Finally, you can run any command, and it will not show up an error. 

React Development

Source 

Now to see the main script, run npm start. 

Reactjs

Source 

Hire Reactjs developers

Source 

  1. Adding Material Design to New React with Babel Project and Webpack

We will add a nice product that implements Google’s Material Design, just with some minor changes. We will add Material Dashboard React to it. 

Get the product first, using the following:

  1. Clone the repo inside another folder

git clone https://github.com/creativetimofficial/material-dashboard-react.git

  1. Download from Github
  2. Download from Creative Tim

At this point, we have both projects, the Material Dashboard React and Webpack and Babel with React. So, we just need to copy the src folder from ‘Material Dashboard React’ into the project. But before anything, we need to add the dependencies from Material Dashboard React’s package.json to our package.json to avoid any errors. 

We need the following: 

npm install –save @material-ui/[email protected] @material-ui/[email protected] @types/[email protected] @types/[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

You can find more here npmjs.com with all details and their own documentation. 

Now, we will copy all contents of the src folder from Material Dashboard React inside our project’s src folder. It will override the index.js file while keeping it in the index.html file. 

Hire Reactjs Developers

Source 

Reactjs Developers

Source 

Just adding some styles and fonts are left, which we will do inside our index.html

<!DOCTYPE html><html lang=”en”>  <head>    <meta charset=”utf-8″>    <meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no”>    <meta name=”theme-color” content=”#000000″>    <link rel=”stylesheet” href=”//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css”>    <script src=”//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js”></script>    <link rel=”stylesheet” href=”https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons”>    <link href=”https://fonts.googleapis.com/icon?family=Material+Icons” rel=”stylesheet”>    <title>React Tutorial</title>  </head>  <body>    <noscript>      You need to enable JavaScript to run this app.    </noscript>    <div id=”root”></div>    <!–      This HTML file is a template.      If you open it directly in the browser, you will see an empty page.      You can add webfonts, meta tags, or analytics to this file.      The build step will place the bundled scripts into the <body> tag.    –>  </body></html>

If we refresh the page, we will see an error ‘Cannot GET/Dashboard.’ The reason is that the routes don’t work. We need to make changes to src/index.js or inside the webpack.config.js. The first option here is pretty easy to understand and apply. 

Now, we will navigate inside the new index.js to change the history type for which we will put createHashHistory(), not createBrowseHistory(). 

Refresh the page, which will not show any error now. 

import React from “react”;import ReactDOM from “react-dom”;import { createHashHistory } from “history”;import { Router, Route, Switch } from “react-router-dom”;import “assets/css/material-dashboard-react.css?v=1.5.0”;import indexRoutes from “routes/index.jsx”;const hist = createHashHistory();ReactDOM.render(  <Router history={hist}>    <Switch>      {indexRoutes.map((prop, key) => {        return <Route path={prop.path} component={prop.component} key={key} />;      })}    </Switch>  </Router>,  document.getElementById(“root”));

That’s All. You have followed all steps correctly, and what we intended to learn is already done. Now apply it and see how it works. 

Need help setting up a dedicated team of Reactjs developers in India? At Your Team In India, we have a pool of certified Reactjs engineers. Connect with us our business head now and get a free consultation.

Subscribe to get regular content updates, and offers

Also Read This

Best Offshore Development Team

Cost-Benefit Analysis of Outsourcing

Offshore Development Centre

Offshore Development Center in India

ODC Centre

HOW IT WORKS?