35,99 €
React 16 Tooling covers the most important tools, utilities, and libraries that every React developer needs to know — in detail.
React 16 Tooling covers the most important tools, utilities, and libraries that every React developer needs to know — in detail. As React has grown, the amazing toolset around it has also grown, adding features and enhancing the development workflow. Each of these essential tools is presented in a practical manner and in a logical order mirroring the development workflow. These tools will make your development life simpler and happier, enabling you to create better and more performant apps.
Adam starts with a hand-picked selection of the best tools for the React 16 ecosystem. For starters, there’s the create-react-app utility that’s officially supported by the React team. Not only does this tool bootstrap your React project for you, it also provides a consistent and stable framework to build upon. The premise is that when you don’t have to think about meta development work, more focus goes into the product itself.
Other React tools follow this same approach to automating and improving your development life. Jest makes unit testing quicker. Flow makes catching errors easier. Docker containers make deployment in a stack simpler. Storybook makes developing components straightforward. ESLint makes writing standardized code faster. The React DevTools plugin makes debugging a cinch. React 16 Tooling clears away the barriers so you can focus on developing the good parts. In this book, we’ll look at each of these powerful tools in detail, showing you how to build the perfect React ecosystem to develop your apps within.
This book is for React developers of any skill level who want to make their lives easier. It helps to have some familiarity with React, but if you are an experienced web developer looking at React, then this book will show you how to build a resilient toolset around you before you begin.
Adam Boduch has been involved with large-scale JavaScript development for nearly 10 years. Before moving to the frontend, he worked on several large-scale cloud computing products, using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems, and the scaling challenges they pose. He is the author of several JavaScript books, including React and React Native published by Packt Publishing, and is passionate about innovative user experiences and high performance.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 273
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Acquisition Editors:Ben Renow-Clarke, Suresh M JainProject Editor: Suzanne CoutinhoContent Development Editor:Monika SangwanTechnical Editor:Bhagyashree RaiIndexer:Mariammal ChettiyarProofreader: Tom JacobGraphics:Tom ScariaProduction Coordinators:Aparna Bhagat, Sandip Tadge
First published: April 2018
Production reference: 1270418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-501-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Adam Boduch has been involved with large-scale JavaScript development for nearly 10 years. Before moving to the frontend, he worked on several large-scale cloud computing products, using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems, and the scaling challenges they pose.
He is the author of several JavaScript books, including React and React Native published by Packt Publishing, and is passionate about innovative user experiences and high performance.
Christopher Pitt is an author, speaker, and developer. He spends most of his time learning new technologies and teaching others about them. He has written about topics, including JS game development, PHP framework usage, and how to create simple compilers.
Christopher helped review the chapters on React 16 and Redux in React 16 Essentials - Second Edition published by Packt Publishing.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
React 16 Tooling
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Creating a Personalized React Development Ecosystem
What's included with React
Components that compare render trees
The DOM render target
Introducing tooling?
Ancillary tasks outside of React
A construction site analogy
React tooling covered in this book
JSX needs to be compiled to JavaScript
Newer JavaScript language features need to be transpiled
Hot module loading to enable application development
Running unit tests automatically
Thinking about type safety
Linting for code quality
Isolating component development environments
Providing a browser-based debugging environment
Deploying React applications
Choosing the right tools
Essential tools
Optional tools
Summary
Efficiently Bootstrapping React Applications with Create React App
Installing Create React App
Creating your first app
Specifying a project name
Automatic dependency handling
Directory structure
Top-level files
Static assets
Source code
Summary
Development Mode and Mastering Hot Reloading
Starting the development server
Webpack configuration
Entry points
Build output
Resolving input files
Loading and compiling files
Configuring plugins
Hot reloading
Hot component reloading in action
Ejecting from Create React App
Summary
Optimizing Test-Driven React Development
The driving philosophy of Jest
Mock everything except the application code
Isolate tests and run in parallel
Tests should feel natural
Running tests
Running tests using react-scripts
Running tests using standalone Jest
Writing Jest tests
Organizing tests using suites
Basic assertions
Basic equality
Approximate equality
Value equality
Values in collections
Working with mocks
Asynchronous assertions
React component snapshots
Unit test coverage
Summary
Streamlining Development and Refactoring with Type-Safe React Components
What does type-safety solve?
Replacing guesswork with assurance
Removing runtime checks
Obvious low-severity bugs
Installing and initializing Flow
Validating component properties and state
Primitive property values
Object property values
Validating component state
Function property values
Enforcing child component types
Parents with specific children types
Parents with one child
Parents with an optional child
Parents with primitive child values
Validating event handler functions
Bringing Flow into the development server
Bringing Flow into your editor
Summary
Enforcing Code Quality to Improve Maintainability
Installing and configuring ESLint
Building on Airbnb standards
Adding React plugins to ESLint
Using ESLint with create-react-app
Using ESLint in a code editor
Automating code formatting with Prettier
Summary
Isolating Components with Storybook
The need for isolated component development
Installing and configuring Storybook
Developing components with stories
Experimenting with props
Experimenting with actions
Linking stories together
Stories as documentation
Building static Storybook apps
Summary
Debugging Components in the Browser
Installing the React Developer Tools add-on
Working with React elements in React Developer Tools
Selecting React elements
Searching for React elements
Inspecting component properties and state
Manipulating element state values
Profiling component performance
Removing reconciliation work
Finding CPU intensive components
Summary
Instrumenting Application State with Redux
Building a Redux app
The App component and state
The Home component and state
The NewBook component and state
The API abstraction
Putting it all together
Installing Redux DevTools
Selecting and examining actions
Action data
Action state trees and charts
Action state diffs
Time travel debugging
Manually triggering actions
Exporting and importing state
Summary
Building and Deploying Static React Sites with Gatsby
Why static React sites?
Types of React apps
Better user experience
Efficient resource usage
Building your first Gatsby site
Adding local filesystem data
Fetching remote data
Summary
Building and Deploying React Applications with Docker Containers
Building a messaging app
Starting Barely SMS
Logging in
The home page
The contacts page
The messages page
Sending a message
The API
Getting started with Node containers
Composing React apps with services
Static React builds for production
Summary
Another Book You May Enjoy
Leave a review – let other readers know what you think
Any given technology is only as good as the tooling that supports it. React is no exception. Although React is just a library from creating user interfaces, the ecosystem that has sprung up around it means that a typical React project has many moving parts. Without the appropriate tooling, you end up spending a lot of time manually performing tasks that would be better off automated by a tool.
React tools come in many forms. Some have been around for a while, others are brand new. Some are found in the browser, others are strictly command line. There are a lot of tools that React developers can use—I've tried to focus on the most powerful tools that have had a direct impact on projects that I've worked on.
Each chapter of this book focuses one React tool. It starts with basic development tools, moves into tools that aid with perfecting your React component design, and finishes with tools for deploying React applications in production.
This book is intended for React developers who are constantly on the lookout for better tools and techniques to up their game. While React experience isn't a strict requirement for reading this book, you'll get the most value if you understand some of the basics of React beforehand.
Chapter 1, Creating a Personalized React Development Ecosystem, introduces the motivations for tooling in React projects.
Chapter 2, Efficiently Bootstrapping React Applications with Create React App, gets you up and running with create-react-app.
Chapter 3, Development Mode and Mastering Hot Reloading, shows you how to develop your React application using a development server and hot module reloading.
Chapter 4, Optimizing Test-Driven React Development, teaches you how to incorporate Jest unit testing into your project.
Chapter 5, Streamlining Development and Refactoring with Type-Safe React Components, introduces type-safety with React components using Flow.
Chapter 6, Enforcing Code Quality to Improve Maintainability, gets you started with ESLint and Prettier—tools for enhancing the quality of your code.
Chapter 7, Isolating Components with Storybook, shows you have to isolate component development from the rest of your application using Storybook.
Chapter 8, Debugging Components in the Browser, goes into depth on the React Development Tools browser plugin to assist with React component debugging.
Chapter 9, Instrumenting Application State with Redux, introduces the Redux DevTools browser plugin, providing you with a clear picture of your application state.
Chapter 10, Building and Deploying Static React Sites with Gatsby, teaches you how to create static websites using Gatsby and React components.
Chapter 11, Building and Deploying React Applications with Docker Containers, shows you how to deploy production-ready React applications to containers.
Learn the basics of React.
If you're already using React in your project, identify missing tools.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/React-16-Tooling. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/React16Tooling_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
When people hear React, they think of a focused library used for efficiently rendering user interfaces. When people hear framework, they think of a large system that might have a few useful tools within it but is otherwise a bloated mess. They're correct about frameworks for the most part, but saying that React isn't a framework is a little misleading.
If you take React out of the box and try to do any meaningful development with it, you'll promptly hit a wall. This is because instead of being distributed as a monolithic framework, React is better described as a core library surrounded by an ecosystem of tools.
The advantage of a framework is that you can install the core library along with the supported tooling in one shot. The downside is that every project is different and you can't be sure what tools you need versus those that you won't. Another advantage to having an ecosystem of tools is that they can evolve independently from one another; you don't have to wait for a new release of the entire framework to get an enhancement for one of the tools that your project uses.
The aim of this book is to show you how to best utilize the tooling ecosystem surrounding React. In this chapter, you'll be introduced to the concept of React tooling by learning the following:
React without tooling
Introduction to tooling
The tools covered in this book
Deciding which tools are needed for your project
Before we dive into tooling discussions, let's make sure that we're on the same page about what React is, and what actually comes with the package when you install it. There are two core React packages required for running React web applications. We'll take a look at these now to provide you with some context for thinking about React tooling.
The first part of the React core is the package called react. This package is what we interface with directly when writing React components. It's a small API—the only time we really use it is when we're creating components with state and we need to extend the Component class.
There's a lot going on under the hood with the react package. This is where the render tree resides and is responsible for efficiently rendering UI elements. Another name for the render tree is the virtual DOM. The idea is that you only have to write JSX markup that describe the UI elements that you want to render while the render tree takes care of everything else:
What you see in this diagram are the components that your code directly interfaces with, and the render tree that takes care of handling presentational changes that result from components that change state. The render tree and everything that it does for you is the key value proposition of React.
The second part of the React core is the Document Object Model (DOM) itself. In fact, the name virtual DOM is rooted in the idea that React is creating DOM representations in JavaScript before it actually talks to the DOM APIs. However, the render tree is a better name because React is creating an AST (short for Abstract Syntax Tree) based on the React components and their states. This is why the same React library is able to work with projects like React Native.
The react-dom package is used to actually translate the render tree into DOM elements in the browser by directly communicating with the browser DOM APIs. Here's what the previous diagram looks like with react-dom included:
This is a nice architecture—it means that you can substitute react-dom for another render target with little effort. As you can see, the core layer of React is minimal. No wonder it's so popular—we can create user interfaces with declarative code that are easy to maintain and are efficient with little effort on our part. With this in mind, let's shift our focus over to the tooling that makes all of this possible.
Tooling isn't unique to React. Every project has its own set of tools that handle tasks related to the core technology so that you don't have to. With frameworks, tooling is baked into the project for the most part. With libraries like React, you get to choose the tools you need versus those that don't play a role in your project.
Now that you know what the React core is, what makes up the rest of the React ecosystem?
Framework bloat is a major turn-off for a lot of people. The reason it feels like bloat is because they have a lot of features that you'll likely never use. React handles this well because it has a clear distinction between the core library and anything else, including things that are essential for React development.
There are two observations I've made about React and the way it's positioned within its surrounding ecosystem:
It's easier to deploy apps that depend on a simple library instead of a framework where all batteries are included
It's easier to think about application development when you have tools that stay out of the way for the most part
In other words, you don't have to use the majority of React tools, but some of them are incredibly helpful.
Any given tool is external to the library you're working with; it's essential to remember this. Tools exist to automate something that would otherwise suck more development time out of our lives. Life is too short to manually do things that can be done for us. I repeat, life is too short for tasks that software can perform better than us. If you're a React developer, take comfort in the fact that there are tools out there for all of the important things that you need to do but don't have time to do.
Perhaps, the ultimate motivator for taking tooling seriously is thinking about what life would be like without the tools that we depend on as professionals. The construction industry is more mature than software and serves as a great example.
Imagine that you are part of a team that's responsible for building a house—an immensely complex undertaking with many moving parts. Now, think about everything that you have to work with. Let's start with the materials themselves. Anything that doesn't have to be assembled on site, isn't. When you're building a house, many components show up partially assembled. For example, sections of roof framing or mixed cement shows up when it's needed.
Then there are actual tools that builders use when putting the house together—simple screwdrivers, hammers, and measuring tapes are taken for granted. What would construction life be like without the ability to create components offsite or the availability of tools to work with everyday construction materials? Would it make the construction of a house impossible? No. Would the process of building it become some unbearably expensive and slow that it'd likely be cancelled before completed? Yes.
Unfortunately, in the software world, we're only beginning to understand how important tooling is. It doesn't matter that we have all the materials and knowledge to build the house of the future. If we don't have the right tooling, it might never be built.
There are literally hundreds of React tools in existence today. The aim of this book, however, is to cover the essential tools for React development. Even with the curated list of tools that you'll learn about in this book, you probably won't use every single one in any given project. Let's take a brief look at the tooling that we'll be looking at throughout the remainder of this book.
React uses a special syntax that resembles HTML to declare components. This markup, called JSX, is embedded in the component JavaScript and needs to be compiled to JavaScript before it's usable by the browser.
The most common approach is to use Babel—a JavaScript compiler—along with a JSX plugin:
The trick is finding a way to make this compilation step as seamless as possible. As a developer, you shouldn't need to concern yourself with the JavaScript output produced by Babel.
Similar to compiling JSX to JavaScript, newer JavaScript language features need to be compiled into versions that are widely supported by browsers everywhere. In fact, once you figure out how to compile JSX to JavaScript, the same process is used to transpile between different versions of JavaScript:
You shouldn't have to worry about the transformed output of your JSX or JavaScript compilation. These are activities better suited for tools to handle, so that you can focus on application development.
Something that's unique to web application development is that it's mostly static content that's loaded into the browser. The browser loads the HTML, followed by any scripts which are then run to completion. There's a long-running process that continuously refreshes the page based on the state of the application—everything is over a network.
As you can imagine, this is especially annoying during development when you want the see the results of your code changes as they're introduced. You don't want to have to manually refresh the page every time you do something. This is where hot module replacement comes into play. Essentially, HMR is a tool that listens for code changes, and when it detects one, it sends a new version of the module to the browser:
Even with a tool like Webpack and its HMR component, it's time-consuming and error-prone to get this setup working correctly, even for simple React projects. Thankfully, there's tooling that hides these setup details from developers today.
You know that you need to write tests for your components. It's not that you don't want to write the actual tests; it's that setting them up so that they're able to run can be a pain. The Jest unit test tool simplifies this because it knows where tests can be found and can run them:
With Jest, we have a place where all of our unit tests go, and each depend on the component that they're testing. This tool knows where to find these tests and how to run them. The result is that we get nice unit test and code coverage output when we need it. There is no overhead beyond actually writing the tests.
JavaScript isn't a type-safe language. Type safety can vastly improve the quality of applications by eliminating the possibility of runtime errors. Once again, we can use tooling to make type-safe React applications. The Flow tool can examine your code, look for type annotations, and notify you when errors are found.
It's one thing to have an application that works; it's another to have an application that works and has maintainable code that doesn't make people's eyes bleed. The best way to achieve measurable code quality is to adopt a standard, like Airbnb's (https://github.com/airbnb/javascript). The best way to enforce coding standards is to use a linter. With React applications, the preferred linting tool is ESLint (https://eslint.org/).
Perhaps the most overlooked tool of React developers is Storybook, which is used for isolated component development. You don't realize it until you're developing your component, but the application can get in the way. Sometimes, you just want to see how the component looks and behaves all on its own:
With a tool like Storybook, it's trivial to provide an isolated context for your component, free of distractions from other components.
Sometimes, looking at unit test output and source code isn't enough to figure out a problem that you're experiencing. Instead, you need to see what's going on as you interact with the application itself. In the browser, you install React tooling that makes it easy to inspect React components as they are related to rendered HTML content.
React also has some built-in performance monitoring capabilities that extend the abilities of the browser developer tools. You can use them to examine and profile your components at a low level.
When you're ready to deploy your React application, it isn't as simple as producing a build and distributing it. In fact, you might not even distribute it at all if you're building a hosted service. Regardless of what the end use case of your application is, there are likely going to be several moving parts in addition to the React frontend. Increasingly, containerizing the main processes that make up your application stack is the preferred approach:
In order to create and deploy React application stacks like this, you'll rely on tools like Docker, especially when it comes time to automate the various deployment scenarios of your project.
If the tooling in the preceding section seemed like a bit much for a single project, don't sweat it. Trying to leverage every possible React tool at the same time is always a mistake. Address one problem at a time, starting with the essentials. As your project moves forward, add in the optional tools to expand your toolset.
There are some React tools that you simply can't live without. For example, browsers don't understand JSX syntax, so this needs to be compiled to JavaScript. As you write code, you'll want to lint it to make sure that basic mistakes aren't missed, and you'll want to run your unit tests. If you try hard enough, you might be able to get by without these tools. But that's the thing—you would spend more effort not using a given tool than to simply embrace it.
As a starting point, find the minimal set of React tools that allow you to make progress. Once your progress noticeably slows, it's time to consider introducing additional tools.
Optional tools are things that you might not get any real value from. For example, you probably won't reap enormous benefits from using Flow to check for type safety or Storybook to isolate component development at the very beginning of a project.
The key thing to remember is that any React tool is optional, and no decisions are permanent. You can always bring in Flow later on, and you can always ditch Storybook if isolated component development isn't your thing.
This chapter introduced you to the concept of tooling in the React ecosystem. You learned that React, at its core, is a simple library and that it depends on the use of several tools to be of any value in the real world. Frameworks try to provide all of the tooling that you'll ever need for your project. While convenient, the needs of the framework users are difficult to predict and can be a distraction from core functionality.
Next, you learned that tooling in React can be a challenge because as a React developer, you're responsible for choosing the right tools and managing their configuration. You then got an overview of the tooling that you'll learn about in more detail throughout the remainder of this book. Lastly, you learned that some tools are critical for React development and you'll need to get them set up right away. Others are optional, and you might not start using them till there's an actual need later on in the life of the project.
In the next chapter, you'll use the Create React App tool to bootstrap a React project.
The first React tool you'll learn about in this book is Create React App. It is a command-line utility that helps you, surprisingly, create a React application. This might sound like something that you shouldn't need much help doing, but when you use this tool, there's a lot of configuration that you no longer have to think about. In this chapter, you'll learn:
Installing the
Create React App
tool on your system
Bootstraping the creation of your React app
What packages are installed when you create a new application
The directory organization and files created with your application
The first step is installing Create React App, which is an npm package: create-react-app. This package should be installed globally because it installs a command on your system that's used to create your React projects. In other words, create-react-app isn't actually part of your React project—it's used to initialize your React project.
Here's how you can install Create React App globally:
$ npm install -g create-react-app
Notice the -g