Setting Up A React ES6 Webpack Project
Pages 616
- Home
- Home
- 10 Steps To Plan Better So You Can Write Less Code
- 5 Steps to organizing a successful Campsite event
- Academic Honesty Policy
- accessibility 101
- Accessing the database from your frontend
- Adding Environment Variables
- Adding Snippets In Sublime Text
- Adding Snippets To Sublime Text
- Advantages and Disadvantages of Javascript
- Algorithm Arguments Optional
- Algorithm Binary Agents
- Algorithm Boo who
- Algorithm Caesars Cipher
- Algorithm Check for Palindromes
- Algorithm Chunky Monkey
- Algorithm Confirm the Ending
- Algorithm Convert HTML Entities
- Algorithm Diff Two Arrays
- Algorithm DNA Pairing
- Algorithm Drop It
- Algorithm Everything be True
- Algorithm Exact Change
- Algorithm Factorialize a Number
- Algorithm Falsy Bouncer
- Algorithm Find The Longest Word in a String
- Algorithm Finders Keepers
- Algorithm Friendly Date Ranges
- Algorithm Inventory Update
- Algorithm Make a Person
- Algorithm Map the Debris
- Algorithm Missing letters
- Algorithm Mutations
- Algorithm No Repeats Please
- Algorithm Pairwise
- Algorithm Pig Latin
- Algorithm Repeat a String Repeat a String
- Algorithm Return Largest Numbers in Arrays
- Algorithm Reverse a String
- Algorithm Roman Numeral Converter
- Algorithm Search and Replace
- Algorithm Seek and Destroy
- Algorithm Slasher Flick
- Algorithm Smallest Common Multiple
- Algorithm Sorted Union
- Algorithm Spinal Tap Case
- Algorithm Steamroller
- Algorithm Style Guide
- Algorithm Sum All Numbers in a Range
- Algorithm Sum All Odd Fibonacci Numbers
- Algorithm Sum All Primes
- Algorithm Symmetric Difference
- Algorithm Title Case a Sentence
- Algorithm Truncate a String
- Algorithm Validate US Telephone Numbers
- Algorithm Where art thou
- Algorithm Where do I belong
- Algorithms Merge Sort
- Angular Resources
- Arithmetic Operators
- Array.isArray
- August 2015 Improvements
- August Live Stream
- Back End Project Resources
- Backend file structure
- beta
- Bobby Tables
- Bonus SocketIO
- Bootstrap
- bot announce
- botdemo
- botintro
- Brownie Points
- Browser Storage
- Camper News
- camperbot
- Campsites
- Capitalize First Letter Of String
- chai
- chai assert
- chai cheat
- Challenge Access Array Data with Indexes
- Challenge Access Multi Dimensional Arrays With Indexes
- Challenge Accessing Nested Arrays In Json
- Challenge Accessing Nested Objects In Json
- Challenge Accessing Objects Properties With Bracket Notation
- Challenge Accessing Objects Properties With The Dot Operator
- Challenge Accessing Objects Properties With Variables
- Challenge Add a Negative Margin to an Element
- Challenge Add a Submit Button to a Form
- Challenge Add Alt Text to an Image for Accessibility
- Challenge Add Borders Around your Elements
- Challenge Add Different Margins to Each Side of an Element
- Challenge Add Different Padding to Each Side of an Element
- Challenge Add Elements within your Bootstrap Wells
- Challenge Add Font Awesome Icons to all of our Buttons
- Challenge Add Font Awesome Icons to our Buttons
- Challenge Add ID Attributes to Bootstrap Elements
- Challenge Add Images to your Website
- Challenge Add New Properties to a JavaScript Object
- Challenge Add Placeholder Text to a Text Field
- Challenge Add Rounded Corners with a Border Radius
- Challenge Add Two Numbers with JavaScript
- Challenge Add your JavaScript Slot Machine Slots
- Challenge Adding A Default Option In Switch Statements
- Challenge Adjust the Margin of an Element
- Challenge Adjusting the Padding of an Element
- Challenge Appending Variables to Strings
- Challenge Apply the Default Bootstrap Button Style
- Challenge Assignment With A Returned Value
- Challenge Assignment with Divided by Equals
- Challenge Assignment with Minus Equals
- Challenge Assignment with Plus Equals
- Challenge Assignment with Times Equals
- Challenge Bring your JavaScript Slot Machine to Life
- Challenge Build JavaScript Objects
- Challenge Call out Optional Actions with Button Info
- Challenge Center Text with Bootstrap
- Challenge Chaining If Else Statements
- Challenge Change Text Inside an Element Using jQuery
- Challenge Change Text with Click Events
- Challenge Change the Color of Text
- Challenge Change the CSS of an Element Using jQuery
- Challenge Change the Font Size of an Element
- Challenge Check Radio Buttons and Checkboxes by Default
- Challenge Check the Length Property of a String Variable
- Challenge Clone an Element Using jQuery
- Challenge Comment out HTML
- Challenge Comment your JavaScript Code
- Challenge Comparison With The Equality Operator
- Challenge Comparison With The Greater Than Equal To Operator
- Challenge Comparison With The Greater Than Operator
- Challenge Comparison With The Inequality Operator
- Challenge Comparison With The Less Than Equal To Operator
- Challenge Comparison With The Less Than Operator
- Challenge Comparison With The Strict Equality Operator
- Challenge Comparison With The Strict Inequality Operator
- Challenge Comparisons With The Logical And Operator
- Challenge Comparisons With The Logical Or Operator
- Challenge Concatenate Strings with .concat
- Challenge Concatenating Strings with Plus Operator
- Challenge Concatenating Strings with the Plus Equals Operator
- Challenge Condense arrays with reduce
- Challenge Construct JavaScript Objects with Functions
- Challenge Constructing Strings with Variables
- Challenge Convert JSON Data to HTML
- Challenge Count Backwards With a For Loop
- Challenge Create a Block Element Bootstrap Button
- Challenge Create a Bootstrap Button
- Challenge Create a Bootstrap Headline
- Challenge Create a Bootstrap Row
- Challenge Create a Bulleted Unordered List
- Challenge Create a Class to Target with jQuery Selectors
- Challenge Create a Custom Heading
- Challenge Create a Form Element
- Challenge Create a JavaScript Slot Machine
- Challenge Create a Set of Checkboxes
- Challenge Create a Set of Radio Buttons
- Challenge Create a Text Field
- Challenge Create an Ordered List
- Challenge Create Bootstrap Wells
- Challenge Create Decimal Numbers with JavaScript
- Challenge Declare JavaScript Objects as Variables
- Challenge Declare JavaScript Variables
- Challenge Declare String Variables
- Challenge Decrement a Number with Javascript
- Challenge Delete HTML Elements
- Challenge Delete Properties from a JavaScript Object
- Challenge Delete your jQuery Functions
- Challenge Disable an Element Using jQuery
- Challenge Ditch Custom CSS for Bootstrap
- Challenge Divide One Number by Another with JavaScript
- Challenge Escape Sequences in Strings
- Challenge Escaping Literal Quotes in Strings
- Challenge Fill in the Blank with Placeholder Text
- Challenge Filter Arrays with filter
- Challenge Find Numbers with Regular Expressions
- Challenge Find the Length of a String
- Challenge Find White Space with Regular Expressions
- Challenge Finding a Remainder in Javascript
- Challenge Generate Random Fractions with JavaScript
- Challenge Generate Random Whole Numbers with JavaScript
- Challenge Generate Random Whole Numbers within a Range
- Challenge Get Geo location Data
- Challenge Get JSON with the jQuery getJSON Method
- Challenge Give a Background Color to a Div Element
- Challenge Give Each Element a Unique ID
- Challenge Give your JavaScript Slot Machine some stylish images
- Challenge Global Scope And Functions
- Challenge Global Vs Local Scope In Functions
- Challenge Headline with the h2 Element
- Challenge House our page within a Bootstrap Container Fluid Div
- Challenge Import a Google Font
- Challenge Increment a Number with Javascript
- Challenge Inform with the Paragraph Element
- Challenge Inherit Styles from the Body Element
- Challenge Initializing Variables with the Equal Operator
- Challenge Introducing Else If Statements
- Challenge Introducing Else Statements
- Challenge Introducing Javascript Object Notation Json
- Challenge Invert Regular Expression Matches with JavaScript
- Challenge Iterate Odd Numbers With a For Loop
- Challenge Iterate over Arrays with map
- Challenge Iterate Through An Array With A For Loop
- Challenge Iterate with JavaScript For Loops
- Challenge Iterate with JavaScript While Loops
- Challenge Join Strings with .join
- Challenge Label Bootstrap Buttons
- Challenge Label Bootstrap Wells
- Challenge Learn how Script Tags and Document Ready Work
- Challenge Line up Form Elements Responsively with Bootstrap
- Challenge Link to External Pages with Anchor Elements
- Challenge Local Scope And Functions
- Challenge Make Circular Images with a Border Radius
- Challenge Make Dead Links using the Hash Symbol
- Challenge Make Images Mobile Responsive
- Challenge Make Instances of Objects with a Constructor Function
- Challenge Make Object Properties Private
- Challenge Make Unique Objects by Passing Parameters to our Constructor
- Challenge Manipulate Arrays With pop()
- Challenge Manipulate Arrays With push()
- Challenge Manipulate Arrays With shift()
- Challenge Manipulate Arrays With unshift()
- Challenge Manipulate JavaScript Objects
- Challenge Modify Array Data With Indexes
- Challenge Multiple Identical Options In Switch Statements
- Challenge Multiply Two Numbers with JavaScript
- Challenge Nest an Anchor Element within a Paragraph
- Challenge Nest Many Elements within a Single Div Element
- Challenge Nest one Array within Another Array
- Challenge Nesting For Loops
- Challenge Override All Other Styles by using Important
- Challenge Override Class Declarations by Styling ID Attributes
- Challenge Override Class Declarations with Inline Styles
- Challenge Override Styles in Subsequent CSS
- Challenge Passing Values To Functions With Arguments
- Challenge Perform Arithmetic Operations on Decimals with JavaScript
- Challenge Prefilter JSON
- Challenge Prioritize One Style Over Another
- Challenge Quoting Strings with Single Quotes
- Challenge Remove an Element Using jQuery
- Challenge Remove Classes from an element with jQuery
- Challenge Render Images from Data Sources
- Challenge Replacing If Else Chains With Switch
- Challenge Responsively Style Checkboxes
- Challenge Responsively Style Radio Buttons
- Challenge Return A Value From A Function With Return
- Challenge Return Early Pattern For Functions
- Challenge Returning Boolean Values From Functions
- Challenge Reverse Arrays with reverse
- Challenge Save your Code Revisions Forever with Git
- Challenge Say Hello to HTML Elements
- Challenge Selecting From Many Options With Switch Statements
- Challenge Set the Font Family of an Element
- Challenge Set the ID of an Element
- Challenge Sift through Text with Regular Expressions
- Challenge Size your Images
- Challenge Solution Template
- Challenge Sort Arrays with sort
- Challenge Specify How Fonts Should Degrade
- Challenge Split Strings with split
- Challenge Split your Bootstrap Row
- Challenge Store Multiple Values in one Variable using JavaScript Arrays
- Challenge Storing Values with the Equal Operator
- Challenge Style Multiple Elements with a CSS Class
- Challenge Style Text Inputs as Form Controls
- Challenge Style the HTML Body Element
- Challenge Subtract One Number from Another with JavaScript
- Challenge Target a Specific Child of an Element Using jQuery
- Challenge Target Elements by Class Using jQuery
- Challenge Target Elements by ID Using jQuery
- Challenge Target Even Numbered Elements Using jQuery
- Challenge Target HTML Elements with Selectors Using jQuery
- Challenge Target the Children of an Element Using jQuery
- Challenge Target the Parent of an Element Using jQuery
- Challenge Target the same element with multiple jQuery Selectors
- Challenge Taste the Bootstrap Button Color Rainbow
- Challenge Testing Objects For Properties
- Challenge Trigger Click Events with jQuery
- Challenge Turn an Image into a Link
- Challenge Uncomment HTML
- Challenge Understand Boolean Values
- Challenge Understand String Immutability
- Challenge Understanding Case Sensitivity in Variables
- Challenge Understanding Uninitialized Variables
- Challenge Updating Object Properties
- Challenge Use a CSS Class to Style an Element
- Challenge Use Abbreviated Hex Code
- Challenge Use an ID Attribute to Style an Element
- Challenge Use appendTo to Move Elements with jQuery
- Challenge Use Bracket Notation to Find the First Character in a String
- Challenge Use Bracket Notation to Find the Last Character in a String
- Challenge Use Bracket Notation to Find the Nth Character in a String
- Challenge Use Bracket Notation to Find the Nth to Last Character in a String
- Challenge Use Clockwise Notation to Specify the Margin of an Element
- Challenge Use Clockwise Notation to Specify the Padding of an Element
- Challenge Use Comments to Clarify Code
- Challenge Use Conditional Logic with If Else Statements
- Challenge Use CSS Selectors to Style Elements
- Challenge Use Hex Code for Specific Colors
- Challenge Use Hex Code for Specific Shades of Gray
- Challenge Use Hex Code to Color Elements Blue
- Challenge Use Hex Code to Color Elements Gray
- Challenge Use Hex Code to Color Elements Green
- Challenge Use Hex Code to Color Elements Red
- Challenge Use Hex Code to Color Elements White
- Challenge Use Hex Code to Mix Colors
- Challenge Use HTML5 to Require a Field
- Challenge Use jQuery to Modify the Entire Page
- Challenge Use Responsive Design with Bootstrap Fluid Containers
- Challenge Use RGB to Color Elements Blue
- Challenge Use RGB to Color Elements Gray
- Challenge Use RGB to Color Elements Green
- Challenge Use RGB to Color Elements Red
- Challenge Use RGB to Color Elements White
- Challenge Use RGB to Mix Colors
- Challenge Use RGB values to Color Elements
- Challenge Use Spans for Inline Elements
- Challenge Use the Bootstrap Grid to Put Elements Side By Side
- Challenge Use the Javascript Console
- Challenge Using Objects For Lookups
- Challenge Using typeof
- Challenge Warn your Users of a Dangerous Action
- Challenge Write Reusable JavaScript with Functions
- Check if an element is hidden using jQuery
- Check if element is hidden js or jquery
- Checkpoint Convert Celsius to Fahrenheit
- Checkpoint Counting Cards
- Checkpoint Golf Code
- Checkpoint Profile Lookup
- Checkpoint Record Collection
- Checkpoint Shopping List
- Checkpoint Stand In Line
- Checkpoint Word Blanks
- Clear Your Browser's Local Storage
- Clone A Specific Branch
- code case
- code formatting
- Code of Conduct
- Coding Help
- CONTRIBUTING
- Contributions Guide with Typo Demo
- Create, Upload and Link Animated GIF Image
- Creating a new API endpoint
- Creating a new directive
- Creating a New Github Issue
- Creating a new route
- css
- css selectors
- Currying
- dau
- debugging
- Debugging JavaScript with Browser DevTools
- Deleting A Branch
- demo trim
- Develop Back End Project locally and run on c9.io
- Disable Code Auto Run
- Django Start Project
- Dotnet
- Dynamic URLs using $routeParams
- Edit or Delete message
- Elixir
- emoji
- Epilogue
- equality vs identity
- example
- Fixing exports.update
- For loops Explained
- Free Code Camp Back End Development Certification
- Free Code Camp completion language requirements
- Free Code Camp Data Visualization Certification
- Free Code Camp Deployment Workflow
- Free Code Camp Front End Development Certification
- Free Code Camp Full Stack Development Certification
- Free Code Camp is an open source community distributed across many platforms
- Free Code Camp JavaScript Style Guide
- Free Code Camp logo
- Free Code Camp's Privacy Policy
- Front End Project Use the Twitchtv JSON API
- Frontend file structure
- Functional Programming Higher Order Functions
- Get info about the current user
- Get Screen Size In Pixels
- Get started with Node_js
- Getting a coding job
- Git Amend Last
- Git Blame
- Git Change the URL of a remote repository
- Git Checkout A Remote Branch
- Git Delete a Branch both locally and remotely
- Git Force Git to overwrite local files on pull
- git merge
- Git Pull Vs Git Fetch
- Git Push Local To Remote Repository
- git rebase
- Git Resources
- Git Shortcut
- Git Undo Redo A Commit
- Gitter
- Gitter Moderation Policy
- global variables
- Go
- Grunt
- Guide Online Contribution
- Guide to Back End Projects Table of Contents
- Guide to Submitting Posts to Free Code Camp Medium Publication
- Gulp Basics
- Help I've Found a Bug
- Help Rooms
- Heroku Deployment Guide
- Higher Order functions
- How Free Code Camp works
- How FreeCodeCamp Nonprofit Projects work
- How GitHub Issue Moderators AKA Issue Mods Work
- How JSONP is different from JSON
- How Long Free Code Camp Takes
- How to add Free Code Camp to my LinkedIn profile
- How to best use the Global Control Shortcuts for Mac
- How to clear specific values from your browser's local storage
- How to clone the FreeCodeCamp website on a Windows pc
- How To Contribute To The Wiki
- How to create a Campsite for your city
- How To Create A Pull Request for Free Code Camp
- How to deploy a website without writing any code at all
- How To Fork And Maintain a Local Instance of Free Code Camp
- How to Get Help on Gitter
- How to get help when you get stuck
- How to get the MEAN stack running locally on OSX
- How To Install Clementine
- How to install Screenhero
- How to know who is in charge of your Campsite on Facebook
- How To Log In To Your Local FCC Site
- how to post code
- How to Rename a Local Branch
- How to share your workspace selfie with FreeCodeCamp on instagram
- How to start when you are stuck (I)
- How to start when you are stuck (II)
- How to start when you are stuck (III)
- How to use the Free Code Camp Wiki
- How you can get to Inbox Zero with Gmail shortcuts
- How you can help to stimulate your city's Campsite on Facebook
- How you can reach the Free Code Camp team to interview them for your publication
- Html and CSS Cheat Sheet
- html elements
- If Free Code Camp is free, how does it make money
- Ignore Files Committed To Git Repo
- IIFE
- Install Django Flask
- Installing WordPress Locally on Mac
- Intro to Yeoman Angular Fullstack Back End Projects
- isLoggedInAsync
- Java
- Java Basics
- Java Introduction
- Java Loops
- Java Resources
- Javascript Callback Functions
- JavaScript Truth Table
- jQuery
- js arguments
- js Array prototype concat
- js Array prototype every
- js Array prototype filter
- js Array prototype forEach
- js Array prototype indexOf
- js Array prototype join
- js Array prototype lastIndexOf
- js Array prototype map
- js Array prototype pop
- js Array prototype push
- js Array prototype reduce
- js Array prototype reverse
- js Array prototype shift
- js Array prototype slice
- js Array prototype some
- js Array prototype sort
- js Array prototype splice
- js Array prototype toString
- js Boolean
- js closures
- JS Comparison Operators
- JS Current URL
- js falsy
- js for in loop
- js for loop
- js for of loop
- js functions
- JS Get Timestamp
- js Global Object
- js immutable
- js loops
- JS Regex Resources
- JS Resources
- js Scopes
- JS Strict Mode
- js String prototype charAt
- js String prototype charCodeAt
- js String prototype concat
- js String prototype indexOf
- js String prototype lastindexOf
- js String prototype match
- js String prototype replace
- js String prototype slice
- js String prototype split
- js String prototype substr
- js String prototype substring
- js String prototype toLowerCase
- js String prototype toUpperCase
- js ternary
- js truthy
- js undefined
- jsonp
- Know it all
- Known Issues With Codepen
- latex
- Learn the basics of the VIM editor
- Linking Your Account with GitHub
- Linux
- List of Free Code Camp city based Campsites
- Loop Protect
- Map
- materializecss framework as a bootstrap alternative
- Math.max
- Math.min
- Math.pow
- medium example wiki article
- More useful APIs
- Mostaganem
- Object.getOwnPropertyNames
- Object.keys
- October 2015 Improvements
- October 2015 Summit Agenda
- Official Free Code Camp Chat Rooms
- ooda
- Other resources that Free Code Camp recommends to nonprofits
- Page redirects using javascript
- Pair programming and why it is special
- parseInt
- Permutations
- Php
- Politica De Honestidad Academica
- Programming Fundamental
- Programming Methodology
- Promises
- Pseudoclassical class definition OOp
- Pull Request Contribute
- PULL_REQUEST_TEMPLATE
- Python
- Python Basics
- Python Functions
- Python Introduction
- Python More Builtin Types
- Python Operators
- Python Resources
- Quick tip keep data in sync
- README
- Reduce made easy
- Refresh Your Browser Cache
- Registering your Nonprofit to Raise Donations through Free Code Camp Commit
- Restrict a page to authenticated users
- RTFM
- Ruby
- Ruby Introduction
- Run Apache Server On A Mac
- Saturday Summit August 2015
- Saturday Summit December 2015
- Saturday Summit November 2015
- Saturday Summit October 2015
- Searching for Your Issue on Github
- Seed data
- Select Issues for Contributing Using Labels
- Setting Up A React ES6 Webpack Project
- Site Improvements August 2015
- Site Improvements October 2015
- Slack
- Spanish Translation Terminology
- staging
- Start Here
- Streaks
- Stream Your Coding Sessions on Twitch.tv
- String.fromCharCode
- String.length
- Swashbuckle Swagger Operation Alphabetical Order
- The main advantages of Free Code Camp
- The Return Early Pattern
- Tips on How To Become A Good Pair Programmer
- topic
- Translating Free Code Camp into Your Native Language
- Translations Guide
- Twitch
- up_and_running_with_sass
- update
- Updates February 11 2016
- using anonymous self executing functions for private namespacing in your js apps
- Using browsec for securing your connection to fcc
- Using Github Pages for your front end development projects
- video demo
- wat
- Web Development in Python
- Web Resources
- What exactly Free Code Camp does
- What pair programming is and why it is special
- What the main advantages of Free Code Camp are
- What the style guide for Algorithms is
- What to do if you speak a language that Free Code Camp does not yet support
- What you will learn, and in what sequence you will learn it
- Why does Free Code Camp use JavaScript instead of Ruby or Python
- Why you need Free Code Camp
- Why You Should Try Pair Programming
- wiki js template
- Wiki Style Guide
- World Language Chat Rooms
- Write and Run ES6 Code in Browser
- writing a markdown file using atom
- Writing great git commit message
- Show 601 more pages…
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links
Clone this wiki locally
Setting up a React, ES6 and Webpack project
This wiki will instruct you how to set up a bare-bones project that uses React, Webpack and ES6. We'll go over getting everything set up in depth.
For this project we will make use of Webpack, which is a module bundler, and is commonly used in React projects.
React goes well with ES6, so we’re going to use ES6 in our code.
ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. -- lukehoban
ES6 doesn’t work in browsers on its own yet, but we can make it work manually using Babel to transpile it to ES5.
A key feature of the technologies we are using is that our index.html
file will refer to one bundled JavaScript file from which we can refer in other JavaScript files, rather than referring to them from the HTML file with script
tags.
Prerequisites
This tutorial is intended to give you a bare bones structure upon which to expand. It should be a good starting point for anyone that wants to learn React and ES6. If you haven’t built anything with JavaScript or jQuery yet, you should go through some of the exercises in the FreeCodeCamp map first.
Before you start, make sure you have NodeJS and Node Package Manager installed at their most recent versions.
Contents
- Initializing the Project
- Installing Dependencies
- File Structuring
- Writing the Code
- Quick Instructions
Initializing the Project
The first thing to do is open our terminal/command line. We need to install Webpack and Webpack Dev Server globally.
npm install webpack webpack-dev-server -g
Installing these modules globally means that we can refer to use their respective command line interfaces in the terminal. Installing Webpack allows us to run webpack
from the terminal to execute a Webpack script. Installing Webpack Dev Server allows us to run a localhost server using our Webpack configuration. This will all become clear a little later.
In your directory of choice, make a new directory, for example react-webpack-example
, and change directory into it:
mkdir react-webpack-example && cd $_
Now that we're in our new directory, we need to create our Webpack file, which will live in the root. This is a configuration file, and so we name it webpack.config.js
.
touch webpack.config.js
Now, we can go ahead and initialise an npm project using the following command:
npm init
We can go ahead and press the enter key to cycle through the options presented to us in the terminal.
The npm init
command will create a package.json
file, which is going to contain important data about our project.
So far, this is what our tree should look like:
.
├── package.json
└── webpack.config.js
If you open your package.json
file, you should see something like this:
{
"name": "react-webpack-example",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Installing Dependencies
Now that we have an empty Webpack Configuration file (webpack.config.js
) and a freshly made Package file (package.json
), we need to install some dependencies. Installing dependencies automatically adds some data to our package.json
.
This project will depend on React, ReactDOM, Webpack, and Webpack Dev Server. It will also depend on a number of Babel packages, because we are going to be writing code using ES6, and Babel is an ES6 transpiler.
The dependencies we require in detail:
Package | Reason |
---|---|
React | 'An npm package to get you immediate access to React, without also requiring the JSX transformer.' |
React DOM | 'This package serves as the entry point of the DOM-related rendering paths. It is intended to be paired with the isomorphic React, which will be shipped as react to npm.' |
Webpack | 'Allows to split your codebase into multiple bundles, which can be loaded on demand.' |
Webpack Dev Server | 'Serves a webpack app. Updates the browser on changes.' |
Babel Loader | 'Babel module loader for Webpack.' |
Babel Core | Required for Babel Loader. |
Babel Preset: ES2015 | Required for Babel Loader. |
Babel Preset: React | Required for Babel Loader. |
We can go ahead and install all these modules with a single command:
npm install --save-dev react react-dom webpack webpack-dev-server babel-loader babel-core babel-preset-es2015 babel-preset-react
If we look at our package.json
file now, we will notice that our devDependencies
has become a list of the Node packages we just installed. This is important because it means we can install these again if we need to using npm install
.
File Structuring
Now it's time to set up our file structure before we write any code.
Firstly, let's create a new file called .gitignore
:
touch .gitignore
This file will contain a list of all the files and folders that are not to be included when we push our project to GitHub. There is a website that serves boilerplate code for .gitignore
files, which is very useful, because often, a .gitignore
file can be rather long and verbose, and we may forget some files or folders that we want Git to ignore.
Go to https://www.gitignore.io/ and type Node
into the search bar, then click Generate
. This will generate a file that looks like this:
# Created by https://www.gitignore.io/api/node
### Node ###
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
Now we can copy and paste that into our .gitignore
file.
Notice that the .gitignore
file should always include node_modules
. This is extremely important, because we don't want to include our node_modules
folder with our Git commits, as they take up a lot of disk space, and can be installed with npm install
, which refers to our package.json
.
Most of the files and folders listed in our .gitignore
file don't exist in our project yet, but if they do in the future, they won't be included in our Git commits, which is important and useful, because we must be selective about what we commit.
Now, we need to make a new folder that will contain the contents of our development code. Let's call it src
:
mkdir src
Then, we need to make a folder that will contain files that we use for production purposes. We'll call this folder dist
:
mkdir dist
Now that we have installed our packages and created empty src
and dist
folders, our tree will look like this (not including .gitignore
, which is a hidden file):
.
├── dist
├── node_modules
├── package.json
├── src
└── webpack.config.js
Now, we can make a new js
folder that goes into our src
folder. This will contain all our React code:
mkdir src/js
We can go ahead and create an empty client.js
in our src/js
. This will be our main React file:
touch src/js/client.js
We also need an index.html
that should not go into our src
folder, rather into our dist
folder, because it is required for the production of our app:
touch dist/index.html
So now, our tree looks something like this:
.
├── dist
│ └── index.html
├── node_modules
├── package.json
├── src
│ └── js
│ └── client.js
└── webpack.config.js
Writing the Code
dist/index.html
We can go now open our dist/index.html
. This will be the one HTML page that loads our entire app. We don't need much code at all for this file, just enough to:
- Set an element for the React DOM in the
src/js/client.js
. - Link to our bundled JavaScript file (which doesn't exist yet).
Therefore, this is what our dist/index.html
file will look like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Webpack Example</title>
</head>
<body>
<!-- React app will be injected into the following `div` element: -->
<div id="app"></div>
<!-- Include bundled JavaScript: -->
<script src="bundle.js"></script>
</body>
</html>
You might be wondering why this page links to a bundle.js
when all we have so far is an empty src/js/client.js
. This will be revealed later when we write our Webpack configuration file.
src/js/client.js
Now it's time to write some React code. Just like in the dist/index.html
file, for now we will write just enough code to get the app going, so there won't be much code required at all:
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
render() {
return (
<div>
<h1>This is one cool app!</h1>
</div>
);
}
}
const app = document.getElementById('app');
ReactDOM.render(<Main />, app);
The code that looks like HTML elements is actually JSX, which is a part of React.
To explain what is going on in this file, we'll break it down:
-
First, we are importing
React
andReactDOM
. These are required for any React file that is used to inject code into the DOM. TheReactDOM
is a virtual DOM, and it's not the same thing as the standard Document Object Model. -
Next, we are creating a React class. Classes were added to JavaScript in ES6. Therefore, this is the ES6 method of writing a React class, but of course we can write one in ES5 too.
Every React class has a
render
method. In this case, therender
method isreturn
ing a JSXdiv
element. This is what we'll see all over any React file. The class can contain other methods which must appear before therender
method, which always goes at the bottom of a class. Lastly, we are linking React with our
index.html
. We set theapp
to be the location of wherever we want our React code to be injected. And finally, using ReactDOM, we inject the component we wrote,<Main />
, into the app, which in this case is thediv
with theid
ofapp
.
webpack.config.js
There's still one more file left to write before our project is ready. It's the Webpack configuration file. At first, webpack.config.js
files can be confusing to look at, but often, they're not as complex as they seem.
In this case, at its most basic, a webpack.config.js
exports an object that has the following properties:
Property | Role |
---|---|
entry | What goes in: the entry point of the app. In this case, it's src/js/client.js . |
output | What comes out: what Webpack is going to bundle for us. In this case, it's whatever we name it in the webpack.config.js . |
loaders | The tasks that Webpack is going to carry out. |
Here is what the webpack.config.js
file looks like:
var path = require('path');
var srcPath = path.join(__dirname, 'src');
var buildPath = path.join(__dirname, 'dist');
module.exports = {
context: srcPath,
entry: path.join(srcPath, 'js', 'client.js'),
output: {
path: buildPath,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
Again, let's break it down so that it's clear what this file is doing:
Firstly, we are requiring NodeJS's
path
module so that we can handle file paths, which is required for setting the object'scontext
. It's very important to use this module rather than try and concatenate directories with strings, because some operating systems, like Windows, require this.Then, we specify a
srcPath
and abuildPath
using thepath
module that we just required. Doing this will ensure we have DRY, readable code.-
Now comes the time to write the object. The properties we are going to use are all relevant to Webpack.
- We first provide a context, which simply specifies where our app is. It refers to the
context
variable that we just created. - We then specify the entry point, which is of course the React app we wrote earlier (
src/js/client.js
). - Next we specify the name of the bundled file that Webpack creates when it runs. In this case it's
dist/bundle.js
. Sound familiar? It should do, because this is the file we are linking to from ourdist/index.html
! - Finally comes the
module
property, which contains an array,loaders
, which currently contains a single object. This object's properties tell Webpack what JavaScript files are being written with ES6 and React, so that its loader,babel
can run accordingly whenwebpack.config.js
is run. This is largely boilerplate code that we can see at the readme page on Babel Loader.
- We first provide a context, which simply specifies where our app is. It refers to the
If webpack.config.js
is confusing now, don't worry, as long as you understand what it is there to do.
Running Webpack and Webpack Dev Server
The time has come to use Webpack. Because Webpack is installed globally, we can run the following in our terminal:
webpack
This will run our webpack.config.js
file. It should run successfully, and we should see something like this appear in our terminal:
Hash: 2474b15611d8d75c5a39
Version: webpack 1.12.14
Time: 1721ms
Asset Size Chunks Chunk Names
bundle.js 679 kB 0 [emitted] main
+ 159 hidden modules
Notice that it refers to an Asset
called bundle.js
. Webpack is telling us that this file has been created when we ran the webpack
command. Check out your dist
folder, and you should see your bundle.js
alongside your index.html
.
Our tree will now look like this:
.
├── dist
| ├── bundle.js
│ └── index.html
├── node_modules
├── package.json
├── src
│ └── js
│ └── client.js
└── webpack.config.js
So now that we have a dist/bundle.js
, our dist/index.html
file is now referring to a file that exists! If we take a look at bundle.js
, we'll see that it's a bundle of all the JavaScript files in our project. Cool!
Go ahead and search for some contents of our dist/bundle.js
, like This is one cool app!
. We can see its context in the file, it's within a weird looking method:
_createClass(Main, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'h1',
null,
'This is one cool app!'
)
);
}
}]);
This is what Babel has done; it has converted the code to ES5 and bundled it among other JavaScript files - including all our Node Modules, of course. Now all our React files can refer to this bundle using ES6 import
statements.
Finally, it's time to check out the app in a browser. For this, we are going to use Webpack Dev Server, which is a feature-rich tool to use for setting up a localhost
server for developing purposes when using Webpack.
Go ahead and run:
webpack-dev-server --content-base dist
We need to include --content-base dist
to specify a content base to Webpack Dev Server, so that it knows where to get files to serve; in this case, it's the dist
folder, because that is the folder that we are using for production as opposed to the src
folder, which we are using for development*.
In our terminal, we should see something like the following:
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /Code/react-webpack-example/dist
Hash: 2474b15611d8d75c5a39
Version: webpack 1.12.14
Time: 3738ms
Following that will be a very long list of all the files bundled into dist/bundle.js
by Webpack. Amazing!
Now is the time to head to the URL provided by that webpack-dev-server
command, http://localhost:8080/
. We should see a page with an h1
that reads:
This is one cool app!
Let's Check out your Elements pane of our Developer Tools. We should have the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Webpack Example</title>
<style type="text/css"></style>
</head>
<body>
<!-- React app will be injected into the following `div` element: -->
<div id="app">
<div data-reactid=".0">
<h1 data-reactid=".0.0">This is one cool app!</h1>
</div>
</div>
<!-- Include bundled JavaScript: -->
<script src="bundle.js"></script>
</body>
</html>
If we this to what we wrote in src/js/client.js
, we will see how React renders into the dist/index.html
.
If you got this far, well done! Now you know how to set up a workspace using React, Webpack and ES6 code, which is awesome, and gives you the starting point for making impressive web apps using cutting edge technologies.
In the next tutorial we will cover some more advanced steps, including:
- Going into more detail with React
- Looking at some other cool features of Webpack, like compiling Sass files
- Using minification on our
dist/bundle.js
Quick Instructions
Here is a list of all the instructions mentioned in this tutorial.
npm install webpack webpack-dev-server -g
mkdir react-webpack-example && cd $_
touch webpack.config.js
npm init
npm install --save-dev react react-dom webpack webpack-dev-server babel-loader babel-core babel-preset-es2015 babel-preset-react
touch .gitignore
- write
.gitignore
(use https://www.gitignore.io/api/node) mkdir src
mkdir dist
mkdir src/js
touch src/js/client.js
touch dist/index.html
- write
dist/index.html
- write
src/js/client.js
- write
webpack.config.js
webpack
webpack-dev-server --content-base dist
- Open Webpack Dev Server route in browser. Done!
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.