Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Progressive Web Apps with React

Create Lightning Fast Web Apps With


Native Power Using React and Firebase
1st Edition Scott Domes
Visit to download the full and correct content document:
https://textbookfull.com/product/progressive-web-apps-with-react-create-lightning-fast
-web-apps-with-native-power-using-react-and-firebase-1st-edition-scott-domes/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Fullstack React Native Create beautiful mobile apps


with JavaScript and React Native 5th Edition Devin
Abbott

https://textbookfull.com/product/fullstack-react-native-create-
beautiful-mobile-apps-with-javascript-and-react-native-5th-
edition-devin-abbott/

React Quickly: Painless web apps with React, JSX,


Redux, and GraphQL 1st Edition Azat Mardan

https://textbookfull.com/product/react-quickly-painless-web-apps-
with-react-jsx-redux-and-graphql-1st-edition-azat-mardan/

React js Essentials A fast paced guide to designing and


building scalable and maintainable web apps with React
js 1st Edition Fedosejev

https://textbookfull.com/product/react-js-essentials-a-fast-
paced-guide-to-designing-and-building-scalable-and-maintainable-
web-apps-with-react-js-1st-edition-fedosejev/

React 16 essentials a fast paced hands on guide to


designing and building scalable and maintainable web
apps with React 16 Second Edition. Edition Boduch

https://textbookfull.com/product/react-16-essentials-a-fast-
paced-hands-on-guide-to-designing-and-building-scalable-and-
maintainable-web-apps-with-react-16-second-edition-edition-
Learning React Native Building Native Mobile Apps with
JavaScript 2nd Edition Bonnie Eisenman

https://textbookfull.com/product/learning-react-native-building-
native-mobile-apps-with-javascript-2nd-edition-bonnie-eisenman/

React Native in Action Developing iOS and Android apps


with JavaScript 1st Edition Nader Dabit

https://textbookfull.com/product/react-native-in-action-
developing-ios-and-android-apps-with-javascript-1st-edition-
nader-dabit/

React Native in Action Developing iOS and Android apps


with JavaScript 1st Edition Nader Dabit

https://textbookfull.com/product/react-native-in-action-
developing-ios-and-android-apps-with-javascript-1st-edition-
nader-dabit-2/

Building Progressive Web Apps Bringing the Power of


Native to the Browser 1st Edition Tal Ater

https://textbookfull.com/product/building-progressive-web-apps-
bringing-the-power-of-native-to-the-browser-1st-edition-tal-ater/

Progressive Web Apps 1st Edition Dean Alan Hume

https://textbookfull.com/product/progressive-web-apps-1st-
edition-dean-alan-hume/
Progressive Web Apps with React

Create lightning fast web apps with native power using React and Firebase
Scott Domes

BIRMINGHAM - MUMBAI
Progressive Web Apps with React
Copyright © 2017 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(s), nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be 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.

First published: October 2017

Production reference: 1181017

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78829-755-4
www.packtpub.com
Credits

Author Copy Editor

Scott Domes Shaila Kusanale

Reviewer Project Coordinator

Amar Gharat Devanshi Doshi

Commissioning Editor Proofreader

Kunal Chaudhari Safis Editing


Acquisition Editor Indexer

Shweta Pant Tejal Daruwale Soni

Content Development Editor Graphics

Onkar Wani Jason Monteiro

Technical Editor Production Coordinator

Akhil Nair Melwyn Dsa


About the Author
Scott Domes is a full stack developer who specializes in React, with a passion for
building powerful and performant web applications, and for playing with shiny new
technologies. Based out of Vancouver, when not coding he's probably out hiking
some mountain, or getting lost in a good book. Scott loves to teach and talk about
web development, and is always looking to learn new things.

A special thank you to Packt Publishing for giving me the chance to write this book,
and for Onkar and Shweta for assisting me on this journey. Check out
https://www.packtpub.com/ for an excellent selection of quality programming books.

Thank you to my technical readers: Warren Vosper, Mario Grasso, Andrew Hayter,
and Miodrag Vujkovic. A special thanks to everyone at MuseFind for their support
and feedback, and to my family and friends for their encouragement.

Lastly, thanks to you, the reader, for picking up this book. I hope you enjoy it. You
can follow me on Twitter and Medium as @scottdomes, or my website,
scottdomes.com
About the Reviewer
Amar Gharat focuses on developing creative and unique web applications using
LAMP, open source, and cutting-edge technology as well as delivering work on time
to meet the deadlines with dedicated team work.

He has a total work experience of 11 years, and has executed projects from design,
development, production, and support. He defines requirements and plans project life
cycle deployment.

He also has knowledge of SDLC and process models, and defines resources and
schedules for project implementation. He plans and schedules project deliverables,
goals, milestones, and tracking them to closure.

Strong leadership and people management are Amar's core skills.

He develops and delivers progress reports, proposals, requirements documentation,


and presentations; submits status reports from the project team, analyzes results, and
troubleshoots problem areas; manages changes in project scope, identifies potential
crises, and devises contingency plans.

He defines project success criteria and disseminates them to involved parties


throughout the project life cycle, and helps build, develop, and grow any business
relationships vital to the success of the project.

Research, innovate, propose, and discuss product area improvements is what he


believes in, and he works on clear requirements with business managers and product
managers. He gets projects developed using agile, and is responsible for code
reviews, documentation, and maintenance of applications. He's also responsible for
core product metrics and end-to-end responsibility for programming of new
pages/microsites.

He develops internal web-based interfaces, and provides technical leadership to team


members. He's known for delivering time-based task assignments, and is an expert in
unit testing.

Amar is also experienced in portal management.


www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
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 service@packtpub.com 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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all
Packt books and video courses, as well as industry-leading tools to help you plan
your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our
editorial process. To help us improve, please leave us an honest review on this
book's Amazon page at https://www.amazon.com/dp/1788297555. If you'd like to join our
team of regular reviewers, you can email us at customerreviews@packtpub.com. We
award our regular reviewers with free eBooks and videos in exchange for their
valuable feedback. Help us be relentless in improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Creating Our App Structure
Setting the scene
The problem
The other problem
Beginning work
Why Progressive Web Apps?
Why React?
A rose by any other name
User stories
Application challenges
Instant loading
Push notifications
Offline access
Mobile-first design
Progressive enhancement
Let's get going
Our app skeleton
CSS and assets
Meta tags and favicons
What is npm?
Node setup
The dark side of npm
Project initiation
Installing React
Using React
Welcome to ReactDOM
Summary
2. Getting Started with Webpack
Our project structure
Welcome to Webpack
Bundling files
Moving our React
Shortcuts
Our Dev server
Webpack loaders
Our first ES6
Splitting up our app
Hot reloading
Building for production
Creating a custom script
Making an asset manifest
Summary
3. Our App's Login Page
What is a React component?
Controversies and Separation of Concerns
Class components versus functional components
Our second component
State in React
Reusing components
Summary
4. Easy Backend Setup With Firebase
What is Firebase?
Firebase gotchas
Setting up
Hiding our API key
Deploying Firebase
Authentication with Firebase
What is a promise?
Back to authentication
Code cleanup
Signing up
Saving our user
Event listeners
Lifecycle methods
Summary
5. Routing with React
The plan
Pages on pages
The React Router difference
Our ChatContainer
Installing React Router
Our BrowserRouter
Our first two Routes
Redirecting on login
Logging out
Detour - higher order components
Our third Route
Summary
6. Completing Our App
User stories progress
ChatContainer skeleton
Managing data flow
Creating a message
Sending a message to Firebase
Our message data
Loading data from Firebase
Displaying our messages
Message display improvements
Multiple users
Batching user messages
Scrolling down
React refs
Loading indicator
The Profile page
Summary
7. Adding a Service Worker
What is a service worker?
The service worker life cycle
Registering our first service worker
Checking for browser support
Listening for the page load
Registering the service worker
Logging out the result
Experiencing the service worker life cycle
Adding Firebase to our service worker
Naming our service worker
Summary
8. Using a Service Worker to Send Push Notifications
Requesting permission
Tracking tokens
Attaching a user to the token
Changing the user inside NotificationResource
Creating a new token
Updating an existing token
Sending push notifications
Writing our Cloud function
Sending to the tokens
Testing our push notifications
Debugging push notifications
Checking the Cloud Functions logs
Checking the Service Worker
Checking the tokens
Summary
9. Making Our App Installable with a Manifest
What is an app manifest?
Browser support
Making our app installable - Android
Manifest properties
Other properties
Linking our manifest
Making our app installable - iOS
App install banners and you
Delaying the app install banner
Listening for the event
Summary
10. The App Shell
What is progressive enhancement?
The RAIL model
Load
Idle
Animation
Response
Timeline
Measuring using the timeline
The Summary tab
Network requests
Waterfall
Screenshots
PageSpeed Insights
The app shell pattern
Moving shell HTML out of React
Moving CSS out of React
Moving the loading indicator
Summary
11. Chunking JavaScript to Optimize Performance with Webpack
The PRPL pattern
Push
Render
Pre-cache
Lazy-load
What is code splitting?
Webpack configuration
Babel stage 1
Conditional imports
Higher-order components
AsyncComponent
Route splitting
Lazy loading
Summary
12. Ready to Cache
What is caching?
The importance of caching
The Cache API
Methods
The asset manifest
Setting up our cache
The install event
Opening up the cache
Fetching the asset manifest
Parsing the JSON
Adding the relevant URLs to the cache
The fetch event
The activate event
Grab the list of cache names
Loop over them
Testing our cache
Summary
13. Auditing Our App
What is Lighthouse?
The criteria
The Audits tab
Our first audit
Evaluating the readout
Using the Lighthouse CLI
Serving our build folder
Using Lighthouse to assess the served page
Logging the results
Summary
14. Conclusion and Next Steps
Next steps
Learning resources
Case studies
Building the Google I/O 2016 Progressive Web App
AliExpress case study
eXtra Electronics case study
Jumia case study
Konga case study
SUUMO case study
Example applications
PWA.rocks
Flipboard
React Hacker News
Notes
Twitter
2048 Puzzle
Articles to read
Native apps are doomed
A BIG list of Progressive Web App tips & tricks
Testing service workers
Twitter Lite and High Performance React Progressive Web Apps at Scale
Why are App Install Banners Still a thing?
A Progressive Web Application with Vue JS
Transforming an existing Angular application into a Progressive Web App
Progressing the Web
Designed Degradations - UX Patterns for Hostile Environments
Instant Loading Web Apps With An Application Shell Architecture
Trick users into thinking your site's faster than it is
Apple’s refusal to support Progressive Web Apps is a detriment to the future of th
e web
Tools
Workbox
Sw-precache
Sw-toolbox
Offline-plugin
Manifest-json
Serviceworker-rails
Sw-offline-google-analytics
Dynamic Service Workers (DSW)
UpUp
Generator-pwa
Progressive-webapp-config
Stretch goals
Switch to Preact
Show online status
Show when typing
Include file upload
Create chat rooms
Interactive without React
Building your own backend
Closing words
Summary
Preface
Progressive Web Apps with React aims to give you everything you need to know
about the future of web development. Progressive Web Apps (PWAs) are
becoming more and more common for companies looking to leverage the best the
web can offer, powered by cutting-edge technologies that bridge the gap between
web apps and native apps.

In this book, we'll leverage the power of the popular JavaScript library React.js to
create a fast and functional UI. Then, we'll add Progressive Web App features such
as push notifications and instant loading, using revolutionary new web technology.
Finally, we'll streamline our app's performance and look at how to best measure its
speed.

By the end of this book, you will feel comfortable with both React and PWAs, and
be ready for the future of the web.
What this book covers
Chapter 1, Creating Our App Structure, gives a brief overview of what exactly you
will be learning to build-- a real-time chat application with push notifications and
offline support. You will get to learn about the challenges that such an app presents,
and get a brief overview of the technologies that will be discussed in this book. By
the end of the chapter, you will set up the application structure of a chat app, with
HTML and CSS.

Chapter 2, Getting Started with Webpack, says that before you write any React code,
you need to set up the webpack build process. In this chapter, you will be introduced
to webpack; you will learn to install the package and set up some basic configuration
as well as get the development server running. This chapter will get you ready to
jump into React.

Chapter 3, Our App's Login Page, introduces you to React time! In this chapter, you
will learn to write the first two components: an App wrapper to contain the
application and a LoginContainer. Learn about rendering with ReactDOM and JSX,
and write a basic form to allow the users to log in. By the end of this chapter, you
will be familiar and comfortable with the React syntax.

Chapter 4, Easy Backend Setup With Firebase, informs that the login form looks great,
but is lacking actual functionality. To move forward, you will need a backend
database and authentication solution to communicate with it. This chapter will
introduce you to Firebase by Google. Set up the application on the Firebase console,
and then program the login and signup functionality for the form.

Chapter 5, Routing with React, lets you know that once the user logs in, you want to
redirect them to the main chat view. Therefore, in this chapter, you will learn to build
that main view and then set up the React Router that allows the users to move
between the pages. Lastly, learn to add a third view the individual user view--and
explore parameter matching in URLs.

Chapter 6, Completing Our App, takes you through the last step in building the basic
application, adding functionality to the chat and user views. You will learn to write
and read data from Firebase, taking advantage of React life cycle methods to do so.
Once that’s done, your web application will be complete, but it’s not quite
progressive yet!
Chapter 7, Adding a Service Worker, covers service workers and how they work.
Here, you'll understand how to register a custom service worker and learn about its
life cycle, and then hook into the default Firebase messaging service worker.

Chapter 8, Using a Service Worker to Send Push Notifications, teaches you to


configure the app now that our service worker is ready, to be able to send the push
notifications. You will use Firebase Cloud Messaging to manage sending these
notifications, and add customization to control how and when they are sent on
desktop and mobile.

Chapter 9, Making Our App Installable with a Manifest, teaches that a manifest is a
JSON file that allows users to save your app to their home screen. You will learn to
create the manifest and understand the best practices as well as iOS-specific
considerations. You will also learn to customize your splash screen and icons.

Chapter 10, The App Shell, puts across the point of the App Shell pattern being a key
concept in PWAs, but what advantages does it bring? You will be introduced to both
the shell and the RAIL system of progressive enhancement, and then move some of
you app's layout out of React for optimal rendering.

Chapter 11, Chunking JavaScript to Optimize Performance with Webpack, explores


the PRPL pattern, its goals and methods, as well as an overview of how to achieve it
in your app. Then, you will dive in, splitting up the JavaScript into chunks based on
routes, and then lazy loading the secondary routes.

Chapter 12, Ready to Cache, walks through how you can leverage the service worker
to achieve offline capability, by understanding the new Cache API, and how to use it
with your service worker to cache the JavaScript chunks.

Chapter 13, Auditing Our App, says it's now time to check our work! In this chapter,
you will be introduced to Lighthouse and understand how to audit PWAs with
Lighthouse.

Chapter 14, Conclusion and Next Steps, Your first PWA is complete! In the
development process, you built most of the PWA infrastructure manually. In this
chapter, you will get to learn about the helper libraries and shortcuts to save time,
and you'll also explore the future of PWA development. Additionally, you will come
across suggestions about the future project ideas and improvements that can be made
to your chat app, as an extra challenge.
What you need for this book
All you require is a computer that can run Node.js (https://nodejs.org/en/download/), a
text editor for writing code, and the latest version of the Chrome browser. If you
want to test your application on mobile, you'll also need an Android or iOS phone.
Who this book is for
This book is for JavaScript developers who want to develop high-performance Web
User interfaces. This book requires basic knowledge of HTML, CSS and JavaScript.
Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning. Code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown
as follows: Inside App.js, we first import the LoginContainer.

A block of code is set as follows:


import React, { Component } from 'react';
import LoginContainer from './LoginContainer';
import './app.css';

class App extends Component {


render() {
return <LoginContainer />
}
}

export default App;

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
if (module.hot) {
module.hot.accept('./components/App', () => {
const NextApp = require('./components/App').default;
ReactDOM.render(
<App/>,
document.getElementById('root')
);
});
}

Any command-line input or output is written as follows:


yarn add css-loader style-loader

New terms and important words are shown in bold. Words that you see on the
screen, for example, in menus or dialog boxes, appear in the text like this: Flip back
to the app, and you should see the Hello from LoginContainer of our
new component.

Warnings or important notes appear like this.


Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book-what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of. To send us general
feedback, simply email feedback@packtpub.com, and mention the book's title in the
subject of your message. If there is a topic that you have expertise in and you are
interested in either writing or contributing to a book, see our author guide at www.pac
ktpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://w
ww.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtp
ub.com/support and register to have the files emailed directly to you. You can
download the code files by following these steps:

1. Log in or register to our website using your email address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

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/PacktPublish
ing/Progressive-Web-Apps-with-React. We also have other code bundles from our rich
catalog of books and videos available at https://github.com/PacktPublishing/. Check them
out!
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books-maybe a mistake in the text or
the code-we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.com/sub
mit-errata, selecting your book, clicking on the Errata Submission Form link, and
entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded to our website or added to any list of
existing errata under the Errata section of that title. To view the previously submitted
errata, go to https://www.packtpub.com/books/content/support and enter the name of the
book in the search field. The required information will appear under the Errata
section.
Another random document with
no related content on Scribd:
Heidän siinä syötyään ja juotuaan ja hyvän tuulen päästyä
vähitellen valtaan vartiat vihdoin uskalsivat kysyä, minkä luostarin
miehiä Syvähenki oli. Tämä nauroi ja virkkoi: …

— Mitä se teille kuuluu, roistot, missä minä asun? Vai kysyttekö


siksi, että voisitte kertoa kenraali Kolle? Mutta hän ei mahda minulle
mitään. Toiset pelätkööt häntä, minä en ainakaan. Jos minä sen
paholaisen tapaisin, niin kyllä selkänsä pehmittäisin!

Vartiat eivät uskaltaneet enää suutaan avata.

Kun he sitten valmistautuivat jatkamaan matkaa, Liu Tshung kysyi


Lo
Talta, mihin tämä aikoi.

Lo Syvähenki vastasi:

— Jos tapat jonkun, muista odottaa, siks' ett' on henki mennyt


menojaan. Mut' jos sa tahdot jonkun pelastaa, niin auta hänet
varmaan asemaan.

— Minä en siis voi jättää teitä, ennenkuin tiedän, että te todella


terveenä olette saapunut Tsang Tshouhun, ei vankina, vaan
vapaana. Sillä Hai Fungiin palaamista ei kannata enää ajatellakaan.

Kun vartiat tämän kuulivat, he virkkoivat hiljaa toisilleen:

— Nyt meidän kävi huonosti.

— Niin. Mitä me nyt sanomme päälliköllemme kotona?

Mutta he eivät mahtaneet sille mitään; heidän täytyi tehdä mitä


Syvähenki käski. Jos hän tahtoi käydä, he kävivät, jos tahtoi
pysähtyä, he pysähtyivät. Vaikka vartiat kohtelivat vapautettua
vankiaan ystävällisesti, niin hän morkkasi heitä, ja jos he
niskottelivat, niin hän löi heitä. Yleensä, heidän täytyi matkalla
käyttäytyä peräti rauhallisesti ja nöyrästi, jos mielivät välttää munkin
suuttumista.

Heti kun he saivat vuokratuksi rattaat, he sijottivat Liu Tshungin


niihin ja kävivät itse jälessä. Iltaisin yövyttiin aikaisin, aamuisin
lähdettiin myöhään taipaleelle ja vartiain täytyi toimittaa palvelijalle
kuuluvat tehtävät, nimittäin, tehdä tulta lieteen, keittää, tarjoilla y.m.s.

Kun Sii ja Tung eräänä päivänä neuvottelivat, mitä he Hai Fungiin


palattuaan tekisivät, sanoi edellinen:

— Minä olen kyllä kuullut puhuttavan eräästä munkista nimeltä


Syvähenki, joka joku aika sitten sai haltuunsa Suuren saarnaajan
luostarin vihannestarhan valvonnan, ja minusta tuntuu kuin tämä
munkki olisi juuri tuo sama mies. Kun olemme vihdoinkin täältä
takaisin palanneet, niin kerromme kaikki mitä on tapahtunut ja
pitäkööt viranomaiset sitten huolta tuosta munkin vietävästä. Mutta
meidän, sinun ja minun, täytyy senjälkeen pysytellä piilossa, kunnes
asia on selvillä.

— Luulenpa, että olet oikeassa, — myönsi toinen ja niin oli


suunnitelma valmis.

Kun he olivat lähes parikymmentä päivää kulkemistaan kulkeneet,


ei Tsang Tshou enää ollut kovinkaan kaukana. Majataloja ei ollut
enää matkan varrella kuin hyvin harvassa. Niinpä he kerrankin
sellaisen puutteessa istuivat tuuhean puun varjoon. Siinä Lo
Syvähenki ilmotti Liu Tshungille, että hänen nyt täytyy erota hänestä,
mutta toivoo jonkun ajan kuluttua jälleen tapaavansa ystävänsä.
— Olkaa hyvä ja käykää Hai Fungiin palattuanne minun appi-isäni
luona ja kertokaa hänelle minun vaiheissani, — pyysi Liu Tshung. —
Entä kuinka saan palkita teidän sanomattoman suuren
hyväntahtoisuutenne?

Mutta Lo Syvähenki ei tahtonut kuulla palkitsemisesta


puhuttavankaan. Auttaakseen Liu Tshungia vielä jonkun päivän
eteenpäin hän antoi tälle kaksikymmentä taelia taskurahoiksi. Vartiat
saivat häneltä myöskin pari taelia sekä seuraavat sanat muistissa
säilytettäväksi:

— Muistakaa, te pahanilkiset, että minä olisin lyönyt päänne puhki,


jollei olisi tämä ystäväni puolustanut teitä. Häntä on teidän siis
kiittäminen siitä, että vielä hengitätte. Mutta nyt te ette saa palata
takaisin, muuten voisitte ruveta halpamaisesti juonittelemaan minua
vastaan…

— Sellaista me emme ikänä voisi edes ajatellakaan, — vastasivat


vartiat. — Ja tämäkin on kenraali Kon syy eikä suinkaan meidän.

Yhtäkkiä pyöritti Syvähenki sauvaansa pari kertaa ympäri ja iski


sillä niin lujasti erään puun runkoon, että puu taittui ja romahti
maahan.

— Kautta Buddhan, noin käy teidän, jos te vähääkään yritätte


juonitella minua vastaani — lisäsi hän osottaen maassa makaavaa
puuta.

Sitten Lo Syvähenki kääntyi Liu Tshungin puoleen sanoen:

— Ystäväni, voikaa hyvin ja onnea matkallenne! — Ja hän kääntyi


ympäri ja läksi astumaan kotiinsa.
Molemmat vartiat seisoivat kuin patsaat paikallaan ja katsoa
tuijottivat hämmästyneinä avosuin hänen jälkeensä.

— Emmekö jatka matkaa? — ehdotti Liu Tshung.

— Siinäpä vasta oli hurja munkki! — ihmettelivät vartiat. —


Yhdellä sauvansa iskulla kaatoi tuollaisen puun!

— Eihän se ole vielä mitään hänen töikseen, — selitti Liu Tshung.


— Olisittepa esimerkiksi nähneet kuinka hän Suuren saarnaajan
luostarissa kerran nykäisi puun juurineen maasta, että multa ilmaan
pöllähti.

Molemmat vartiat nyökäyttivät toisilleen päätään kuultuaan


luostarin nimen, ikäänkuin olisivat tahtoneet sanoa:

— Sieltä oli se munkki siis kuitenkin.

Loppusananen Lo Tan myöhemmistä vaiheista.

[Tapausten kulku työntää nyt sankarimme syrjään. Se, mitä


muitten asiain yhteydessä ja lomassa hänestä myöhemmin
kerrotaan, on tähän koottu lyhykäiseksi loppusanaseksi.]

Syvähenki — eli Lo Ta — oli sillä välin palannut takaisin Hai


Fungiin, Suuren saarnaajan luostariin. Mutta kuten saattoi
odottaakin, hänen asemansa muuttui pian hyvin epävarmaksi, kun
kerran tuli tunnetuksi, että hän oli auttanut hirmuvaltaisen hallituksen
uhrin vapaaksi. Mutta ystäväinsä, noitten laiskottelevien
maankulkijain kautta, hän sai viime hetkessä tiedon uhkaavasta
vaarasta ja pakeni keskellä yötä siinä rymäkässä, minkä
sytyttämänsä rakennuksen palo herätti johtaen viranomaisten
huomion toisaalle.

Hän pakeni pohjoiseen ja tapasi siellä jonkun ajan kuluttua Liu


Tshungin sekä useita muita vanhoja tuttaviaan, jotka olivat yhtyneet
kapinaan hallitusta vastaan. Hän liittyi heti näihin ja saavutti
voimallaan ja jalomielisyydellään hyvän maineen kapinoitsijain
keskuudessa.

Nyt toteutui vähitellen luostarinjohtaja Tshi Tshinin ennustus


Syvähengen »hyvistä töistä». Hän liittyi nimittäin siihen
sankarijoukkoon, joka tuli tunnetuksi nimellä »Satakahdeksan» ja
jonka jäsenet olivat Lo Tan tavoin aikaisemmin monta kovaa
kokeneet ja monta vaarallista seikkailua suorittaneet. Tämä joukko
asettui kapinallisten etupäähän Lo Liang-virran varsilla. Turhaan
yrittivät hallituksen joukot saada haltuunsa heidän miehittämiään
vuoria. He palauttivat monta seikkaa entiseen hyvään kuntoon,
hyökkäsivät kaikkein lujimmin linnoitettuja kaupunkeja vastaan ja
vapauttivat monen monta uhria sortajain hirmuvallasta. Näitten
»sadankahdeksan» joukossa oli kolmekymmentakuusi ensi luokan
tähteä, m.m. Lo Ta, Shi Tsun ja Liu Tshung, sekä
seitsemänkymmentäkaksi toisen luokan tähteä, joihin m.m. Li Tshing
kuului.

Useat kerrat Lo Ta oli menettää henkensä. Kerran antoi eräs


vaimo, joka miehensä kanssa piti ravintolaa ja oli salaisessa
yhteydessä muutaman rosvojoukon kanssa, hänelle myrkkyä. Mutta
silloin sattui ravintoloitsija itse tulemaan kotiin. Kun tämä huomasi Lo
Tan sankarillisen ryhdin ja muodon ja katseli hänen suurta rautaista
sauvaansa ja mahtavaa miekkaansa, hän tunsi toverillista
myötätuntoa Lo Taa kohtaan ja pelasti hänet antamalla
vastamyrkkyä. Useammin kuin kerran hän joutui vangiksi, kun hän
jalon luonteensa innostamana koetti omin voiminsa vapauttaa jonkun
ystävän linnoitetusta kaupungista tai vihollisen leiristä. Mutta milloin
hänen personalliset voimansa eivät riittäneet ylivoimaisiin urotöihin,
hänen asetoverinsa pitivät huolta siitä, että apua tuli ajoissa.
Katurosvoilemiseen Lo Ta ei kuitenkaan ottanut koskaan osaa,
vaikka useat hänen tovereistaan eivät siitä paljon välittäneet, jos
ryöstivätkin.

Kun tataarit sitten jonkun ajan kuluttua nousivat maan herroiksi,


hän olisi heidän hallitessaan saanut helposti korkean, hyvätuloisen
viran jo senkin vuoksi, että oli syntyperältään lähempää sukua
tataareille kuin kiinalaiselle rodulle. Mutta häntä ei miellyttänyr enää
virkamiehenä olo, vaan nyt hän todellakin kaipasi rauhaa. Tästä
syystä hän uudisti tuttavuutensa Kirsikkamajan vanhan Liun kanssa,
jonka tyttären hän aikoinaan oli pelastanut rosvokuninkaan käsistä,
ja nai nyt kaikkien asianomaisten suostumuksella tämän tytön.
Hänen ei tarvinnut enää käyttää munkinpukua eikä hän koskaan
ollutkaan tuntenut mieltymystä tähän säätyyn. Niinpä hän nyt siis
heitti valepukunsa ja Syvähenki-nimensä ja valitsi niitten sijaan kelpo
vaimon. Talonpoika Lo astui talonpoika Liun sijaan, jonka hän
myöskin saattoi hautaan. Voittipa Lo Ta — kukapa olisi sitä uskonut?
— naapuriensa keskuudessa rauhallisen ja raittiin miehen maineen.
Kun hänen vanhat ystävänsä useita vuosia myöhemmin sattuivat
tapaamaan hänet matkoilla tai kävivät hänen luonaan
Kirsikkamajassa, hänen oli tapana heille kertoa, miten tämä tapahtui:

— Pian senjälkeen kun olin asettunut tänne, minun täytyi asioitteni


tähden tehdä matka läheisimpään kauppalaan. Silloisen tapani
mukaan minä pistäydyin ravintolaan kohtaamaan tuttaviani ja join
itseni juovuksiin. Kukkarossani sattui olemaan runsaasti rahaa ja
olisipa joku saattanut varastaa ne minulta, jollei eräs hyvä ihminen,
jonka nimeä en koskaan tullut tietämään, olisi ottanut niitä minulta
talteen minun maatessani humalassa kyläravintolan lattialla. Hän vei
rahat vaimolleni kotiini, kertoi hänelle missä ja millaisessa tilassa
minä olin, punnitutti rahat, jotta nähtäisiin, ettei hän ollut pitänyt niistä
mitään, ja läksi pois. Hänen lähdettyään riensi vaimoni, joka on helmi
kaikkien vaimojen joukossa, minun luokseni, niin kaukana kuin
kyläravintola olikin. Kun vaimoni astui sisään, niin minä tunsin hänen
suloisen äänensä, vaikka olinkin aika humalassa, ja hän alkoi hoitaa
minua hellästi kuin lasta. Vähitellen minä siitä selvisin ja halusin
lähteä kotiin. Hän talutti minua kädestä eikä lausunut koko matkalla
moitteen sanaa, vaan jutteli kauniisti kanssani. Ja siitä päivästä
saakka — lopetti Lo Ta riemuiten, — ei ole vaimoni koskaan voinut
sanoa, että olisin juovuksissa ollut. Ja vaikka siitä on jo
kaksikymmentä vuotta kulunut, ei hän ole koskaan nähnyt minua
edes hienossakaan hiprakassa. Minä kiitän tästä kyllä Buddhaa,
mutta enemmän vielä kelpo vaimon rakkautta. Ennenkuin minä sen
opin tietämään, olin narri, vieläpä pahempaakin — murhamies.
Taivas suokoon sen minulle anteeksi!
*** END OF THE PROJECT GUTENBERG EBOOK KAPINALLINEN
LO TA ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund from
the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law in
the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms of
this agreement by keeping this work in the same format with its
attached full Project Gutenberg™ License when you share it without
charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears, or
with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning of
this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1 with
active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or expense
to the user, provide a copy, a means of exporting a copy, or a means
of obtaining a copy upon request, of the work in its original “Plain
Vanilla ASCII” or other form. Any alternate format must include the
full Project Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in paragraph
1.F.3, the Project Gutenberg Literary Archive Foundation, the owner
of the Project Gutenberg™ trademark, and any other party
distributing a Project Gutenberg™ electronic work under this
agreement, disclaim all liability to you for damages, costs and
expenses, including legal fees. YOU AGREE THAT YOU HAVE NO
REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF
WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE
PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE
FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving it,
you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or entity
that provided you with the defective work may elect to provide a
replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and distribution
of Project Gutenberg™ electronic works, harmless from all liability,
costs and expenses, including legal fees, that arise directly or
indirectly from any of the following which you do or cause to occur:
(a) distribution of this or any Project Gutenberg™ work, (b)
alteration, modification, or additions or deletions to any Project
Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many small
donations ($1 to $5,000) are particularly important to maintaining tax
exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.

Project Gutenberg™ eBooks are often created from several printed


editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like