Giter Club home page Giter Club logo

webpack-and-react-dc-web-031218's Introduction

Webpack and React

Overview

In this lesson, we'll unpack what Webpack brings to the table when developing React applications.

Objectives

  1. Learn what Webpack is
  2. Learn how Webpack integrates with React
  3. Frame Webpack's relative importance at this stage in learning React

Webpack

Welcome back! We are picking up where we left off in the previous lesson. If you didn't take a break, shame on you. In this lesson, we will explore Webpack and its place in the React development process.

The Problem

To best describe Webpack, we will begin by describing the problem that it was created to solve.

Picture having a server that sends some JavaScript using webpage to browsers. Let's imagine we have some animateDiv.js script we want browsers to receive that itself makes use of jquery. The first file we send to a requesting client, index.html, may look like this:

<!-- index.html -->
<html>
  <head>
    <meta charset="utf-8">
    <script src="jquery.js"></script>
    <script src="animateDiv.js"></script>
    <title>Discotek</title>
  </head>
  <body>
    <div class="animat" onclick="animateDiv.js">
      I'm going to animate if you click me!
    </div>
  </body>
</html>

With this approach, we are actually making three http requests to the server for the application:

  • We hit the base url and are returned the index.html file
  • index.html tells the browser to request jquery.js from the server
  • index.html tells the browser to request animateDiv.js from the server

A quick and dirty way around this would be to either combine our JavaScript files into one file on the server (bringing this to two requests):

<!-- index.html -->
...
<script src="combinedJqueryAnimateDiv.js"></script>
...

We could go one step futher and even in-line the JavaScript directly into our HTML in a <script> tag (sending everything at once in index.html):

<!-- index.html -->
...
<script>
  // all the contents of jquery.js and animateDiv.js written directly here!
</script>
...

In the last couple of labs we have been using npm start to run our code in the browser and npm test to run our tests. The commands have been running Babel and Webpack to transpile our code into executable JS for all browsers.

Webpack lets us require modules using Node's version of the CommonJS module system. This means that we can include external JS code in our JavaScript files (both local files as well as node_modules installed with npm). In a simplified example:

  • File siliconOverlord.js has space-age AI code in it
  • File enslaveHumanity.js wants to make use of this other file and send it to browsers all over the internet.
  • Instead of always sending both enslaveHumanity.js and siliconOverlord.js to browsers, one after the other, Webpack pre-bundles them together into a single file that can be sent instead: singularity.js

If you have been working with dependencies already (gems in rails, require in vanilla JS, etc.) you may have noticed we did not need any tool like Webpack to work with code written in other files. While this is true, and we don't need Webpack to do this, let's highlight the problem Webpack solves before trying to understand it:.

When compiling a React application with Webpack, it'll check every file for dependencies that it needs to import, and also include that code. In more technical terms, it's traversing the dependency tree and inlining those dependencies in our script. What we'll end up with is one big JS file that includes all of our code, including any dependencies (like React, your components, your npm modules, etc.) in that file too. The convenience of this is not to be underestimated: one file, with all of our code, means we only need to transfer a single thing to our clients when they ask for our React applications!

Enough theory, let's take a look at a rudimentary example of how Webpack does this. Let's assume we have the following application on our server that we want to share with the world:

Simplified Webpack example

The files we want our client to have, which constitute one whole dank web application:

// reveal.js (pre Webpack digestion)
function reveal(person, realIdentity) {
  person.identity = realIdentity
}

export default reveal
// main.js (pre Webpack digestion)
import reveal from './reveal.js'

const gutMensch = {
  name: "Andrew Cohn",
  identity: "Friendly Neighborhood Flatiron Teacher",
}

reveal(gutMensch, "Chrome Boi")

Without Webpack, we would need to find some way to send both files to our client and ensure they are playing nicely together. We couldn't just send the main.js file wizzing over the internet, through a series of tubes, to our client expecting it to make use of the reveal function: the client hasn't even received the reveal.js file in this case! While we have several ways we could make this work, most of them are headaches and someone else has already made an excellent solution: Webpack.

Instead of writing our own bespoke, artisanal, Etsy™ sell-able dependency solution, we can just use Webpack!

The result after we unleash Webpack on these files:

// bundle.js (post Webpack digestion)
function reveal(person, realIdentity) {
  person.identity = realIdentity
}

const gutMensch = {
  name: "Andrew Cohn",
  identity: "Friendly Neighborhood Flatiron Teacher",
}

reveal(gutMensch, "Chrome Boi")

If we were to first pre-digest our files with Webpack, we would instead have a single, all-encompassing, file that ensures our dependencies are right where they belong.

TODO: removed the code along/named export part that was here (see curriculum/react-jsx repo). Check lab and put there? Don't want to reincorporate: long enough as it is.

Summary

You have just read a lot of information about a tool you likely have not worked directly with before. Luckily, its straight forward to summarize:

In React, Webpack manages pesky dependency loading for us by pre-digesting our many files' code and outputting a single 'bundle', which contains all of our code, with dependencies properly placed, in one file.

Looking Forward

After reading the previous lesson on Babel and now this one on Webpack, you may, understandably, be asking yourself:

  • "How important is this Webpack/Babel jargon?"
  • "How much do I need to learn about the different tools that improve React development experience vs. actual React programming?"
  • "Why on Earth did I ever npm run eject?"
  • "Day 36: Dear Diary, I have grown ever more suspicious of what create-react-app is hiding from me. I am going to do it..."

Because create-react-app is so opaque with configuration files, allow us to to transparent with you:

At Flatiron, we are constantly balancing an explanation of the fundamentals against practice on the real skills that will get you producing valuable applications the quickest. We believe that, while learning React basics, it's important to know how these tools (Webpack + Babel) work on a high level. Let's justify both in turn:

Most React code nowadays is being compiled one way or another — be it using Webpack, an alternative such as Browserify, or something else. We want to use it, but we don't want to create unnecessary busywork for ourselves or distract with peripherals.

Additionally, there are a lot of juicy nectarines (read: low hanging fruit) that aren't present in the the ECMAScript version browsers implement, i.e.: JSX, upcoming proposed language features, etc., which we can pluck with Babel. Don't you want to sink your teeth into those syntactic sugary stone fruits?

Every lab from now on in this section will have these tools set up for you. You just need to run npm start to complete the Babel compiling, Webpack bundling, process. Additionally, npm run watch will initiate 'hot reloading', which re-pushes your application to the browser anytime you save files you are working on. This will streamline the development process. In layperson terms, if React development skills were muscles, we want to focus on getting you swol before having you worry about learning to assemble weight machines.

Resources

View Webpack and React on Learn.co and start learning to code for free.

webpack-and-react-dc-web-031218's People

Contributors

danielseehausen avatar saturdayam avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.