Webpack 4 React JS Configuration

Configuring the React with Webpack 4 is now made very easier. Webpack 4 can also work like Parcel JS’s zero config build system. But configuring Webpack 4 on top of React may seem a bit of mystery for beginners. So let’s dive into the tutorial…

First install the dependencies for React JS:

npm install --save react react-dom

Then install dev dependencies Webpack:

npm install --save-dev webpack webpack-cli babel-loader babel-preset-env babel-preset-react css-loader extract-text-webpack-plugin@next file-loader

Add a new file named `webpack.config.js` in your root folder and add the following configurations:

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  mode: "development",
  watch: true,
  entry: "./src/index.js",
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: "babel-loader",
        options: {
          presets: ["react"]
        }
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: "css-loader",
          options: {
            modules: true
          }
        })
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: "file-loader",
        query: {
          name: "[name].[ext]?[hash]"
        }
      }
    ]
  },

  plugins: [new ExtractTextPlugin("style.css")],

  resolve: {
    extensions: [".js", ".json", ".jsx"]
  }
};

Lets update our package.json by adding the following commands inside script section:

...
"scripts": {
  "webpack": "npx webpack --config webpack.config.js",
  "build": "npx webpack -p --config webpack.config.js"
}
...

You are almost done now.

Just enter the command `webpack` when developing, which will bundles all of your assets without compression.

And for the production build, use the command `npm run build`.

If you stuck anywhere following the tutorial, just add a comment, am more than happy to help you, thank you 🙂

How to use Google Calendar API with React JS

First goto Google Cloud console and get your Google API Key and head over to Google Calendar and grab your Calendar ID from settings, and also make sure the calendar is enabled to be publicly accessible.

First include the Google API script at the bottom of your body tag in index.html

https://apis.google.com/js/api.js

Create a new React component and define a state variable named events as an array.

class App extends React.Component{
  constructor(props) {
    super(props)
    this.state = {
      events: []
    }
  }
  ...
}

And then create a function named getEvents() which be can called during ComponentDidMount lifecycle of React JS.

componentDidMount = () => {
  this.getEvents();
}

Let’s define our getEvent function, which make call to Google Calendar API and update the state with response.

getEvents(){
  let that = this;
  function start() {
    gapi.client.init({
      'apiKey': GOOGLE_API_KEY
    }).then(function() {
      return gapi.client.request({
        'path': `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
      })
    }).then( (response) => {
      let events = response.result.items
      that.setState({
        events
      }, ()=>{
        console.log(that.state.events);
      })
    }, function(reason) {
      console.log(reason);
    });
  }
  gapi.load('client', start)
}

The function gapi.load is used to load gapi libraries. It needs two params. First one for libraries and second one is a callback function which can be triggered once the requested libraries are loaded.

We have given start as a callback function, which will initializes the JavaScript client with API key.

Once the client is initialised, we will call the request method which will take the Google Calendar API’s rest URL.

https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events

The above API endpoint will fetch all the events from calendar.

Once the request promise is resolved we will get the list of events as response. Then we will call setState method of React to store data to the app state.

Then we can render the list of events inside our app using code below:

...
render(){
  return(
    {this.state.events.map(function(event){
      return(
        
          {event.summary} {event.start.dateTime} - {event.end.dateTime}
        
      )
    });
  )
}
...

That’s it you have successfully integrated Google Calendar API with React JS.

You can find the complete code here and demo here.

How to use source-map-explorer with webpack

Source Map Explorer is a bundle analyzer tool which shows treemap visualizaton of your component sizes. Check it’s Github for more expalanation.

Let’s see how we can use source-map-explorer with webpack.

First install source-map-explorer globally using npm

npm install -g source-map-explorer

Now go to your project folder and make sure you have a sourc emap file for your bundle.js. It will named like this, bundle.js.map

If the source map file is not available, you can easily generate it by configuring devtool option in webpack.

Open webpack.config.js and add devtool: ‘source-map’ after output configuration.

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

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Hereafter you will be generating source maps along with your bundle.js

Now just run the following command to see the magic of source-map-explorer

source-map-explorer bundle.js bundle.js.map

Here is how it will took,

sourcemap-explorer

sourcemap-explorer