Top Banner
Extracted from: Modern Front-End Development for Rails Webpacker, Stimulus, and React This PDF file contains pages extracted from Modern Front-End Development for Rails, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printed versions; the content is otherwise identical. Copyright © 2019 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Raleigh, North Carolina
10

Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

May 22, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

Extracted from:

Modern Front-End Developmentfor Rails

Webpacker, Stimulus, and React

This PDF file contains pages extracted from Modern Front-End Development forRails, published by the Pragmatic Bookshelf. For more information or to purchase

a paperback or PDF copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; the

content is otherwise identical.

Copyright © 2019 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,

without the prior consent of the publisher.

The Pragmatic BookshelfRaleigh, North Carolina

Page 2: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific
Page 3: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

Modern Front-End Developmentfor Rails

Webpacker, Stimulus, and React

Noel Rappin

The Pragmatic BookshelfRaleigh, North Carolina

Page 4: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.

Our Pragmatic books, screencasts, and audio books can help you and your team createbetter software and have more fun. Visit us at https://pragprog.com.

For sales, volume licensing, and support, please contact [email protected].

For international rights, please contact [email protected].

Copyright © 2019 The Pragmatic Programmers, LLC.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording,or otherwise, without the prior consent of the publisher.

ISBN-13: 978-1-68050-721-8Encoded using the finest acid-free high-entropy binary digits.Book version: B1.0—October 30, 2019

Page 5: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

So, You Want to Write Some Client-SideCode

“I need a web site,” the client said.

“Great,” you think. Rails is a solid way to go. It’s still the best way for a smallteam to be as productive as a big team. You are ready for this. You startthinking of estimates…modeling data structures…

“I want it to look cool, with lots of stuff moving around, and be really interac-tive,” the client added.

“Ugh,” you think. That brings in JavaScript. And with it, a lot of decisions.What language? There’s not just JavaScript, but a host of languages thatcompile to JavaScript: TypeScript, Elm, ClojureScript. What framework? Thereare dozens: React, Vue, Ember, Stimulus, Svelte, Preact, and on and on. Howto package the code and CSS? There’s the Rails asset pipeline and Webpacker.

Suddenly you are overwhelmed by the added complexity.

But Rails can help with the client side, too. Ruby on Rails version 6 has toolsthat help you interact with the JavaScript ecosystem to build an exceptionalfront-end experience. In this book, I’ll show you how you can enhance theuser experience of a standard Rails application using front-end tools fromthe Rails ecosystem (Webpacker and Stimulus) as well as with tools from theJavaScript ecosystem (webpack, TypeScript, and React) and create a greatRails-based app.

So that interactive web site your client wants? No problem.

Basic AssumptionsRails is an opinionated framework, and this is an opinionated book. In prac-tice, being opinionated means Rails makes certain tasks easier if you arewilling to structure your program the way the Rails core team thinks you

• Click HERE to purchase this book now. discuss

Page 6: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

should. For this book, being opinionated means not trying to show you everypossible way Rails and JavaScript can combine, but instead focusing on thetools I think will be most useful. I’ve already embedded an important opinion:that we’re going to use JavaScript to enhance a Rails application rather thanuse JavaScript to build a completely separate single-page application (SPA)that does not depend on Rails tools.

My basic argument for not writing an SPA is that Rails and standard browserbehavior handle a tremendous amount of complexity for you, and moving toan SPA structure requires you to build in much of that functionality yourself.Over time, the front-end frameworks have gotten better at handling thecomplexity for you, but for now and for my money, Rails still manages thiscomplexity better.

That said, there are legitimate places where an SPA might make sense. If youruser experience is so different from the normal web structure that the existingbehavior of Rails and the browser isn’t much help, then an SPA begins tolook attractive. If your back end is already an application programminginterface (API) supporting a mobile app or external services, then an SPA canalso act as a consumer of that API, saving you from duplicating view-layerlogic. However, my experience is that most of the time, for most teams,starting by leveraging the Rails view and browser features is the best way tocreate a great application.

Within that assumption—Rails back end with some front-end interac-tion—there’s still a wide range of tools, architectures, and techniques thatmight be appropriate for the application. We’re going to navigate that space.Within that space, we are going to explore different ways of structuring aRails/JavaScript collaboration.

Let’s Build an AppBefore we start talking about front-end structure, we need to have an app toattach all that front-end structure to. I’ve created a sample app for a fictionalmusic festival called North By North South, where multiple bands will performat various concerts during the event. This app contains a schedule of all ofthe concerts and venues. There isn’t really much to this app; I’ve used Railsscaffolding for a minimal amount of administration, but it’s basically just astructure that lets us get at the two pages we’ll be managing in this book: theschedule page and the concert display page.

The schedule page shows all the concerts, acts, and times for the entire festi-val. We’ll be adding features to this for some basic show-hide behavior, and

So, You Want to Write Some Client-Side Code • iv

• Click HERE to purchase this book now. discuss

Page 7: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

some more complex filters. We’ll also use this page to show how to deal withcalling Rails from the front end.

The concert view page lets you see a simplified theater diagram for eachindividual concert and build a ticket purchase. We’ll use this page to addsome more elaborate client-side behavior that goes beyond augmented forms.

The data model for the app looks like this:

• The festival includes several concerts that take place at a particular starttimes.

• Each concert has a venue, and each venue has a number of rows and anumber of seats per row (which I realize is vastly simplified from realmusic venues, but we’re just going to pretend for now because that getsvery complicated very quickly).

• Each concert has one or more gigs that make up the concert.• Each gig matches a band to a concert, and has a start order and a dura-

tion.• Each concert has a bunch of sold tickets, which link a concert to a partic-

ular row and seat in the venue.

Here’s a diagram of the data model:

ConcertVenue

(rows)(seats per row)

1*

Gig

1

*

Band1 1

Tickets

1

*

The app uses the Bulma CSS framework https://bulma.io, which I picked becauseit’s attractive, adds relatively few class names to the markup, and it’s usuallypossible to figure out what the CSS does from the class names.

If you’d like to follow along with the application throughout the course of thebook, you can download the sample code files from the book page on thePragmatic Bookshelf website:

https://pragprog.com/book/nrclient

• Click HERE to purchase this book now. discuss

Let’s Build an App • v

Page 8: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

The code uses PostgreSQL, so you’ll need to have that set up on your machine.

If you download the code and run bin/setup.rb, that should install the Rubydependencies on a Mac, Linux, or Windows/Bash setup, and also seed thedatabase with a bunch of random startup data.

With the app set up, if you run it using rails s, and hit http://localhost:3000, you’llsee the schedule page, with a bunch of dates at the top, a search field in themiddle, and a lot of schedule information at the bottom, with each scheduledday having a kinda ugly button labeled “Hide.” If you click on any of theconcert names, you’ll be taken to a concert page that shows basic data aswell as a grid of sets for the show. Neither of these pages has any interactivityat the moment.

The schedule page should look something like this (your randomized datawill be different):

If you want to keep following along, each separate step in the application isa different directory in the sample code download, and you can move fromone to another to see the entire application at different steps.

The Tools We’ll UseOver the course of the book, we’ll walk through the basics of getting Rails setup to use Webpacker to serve JavaScript and CSS to the browser. Then wewill write some code to get the browser to do things. We’ll talk primarily about

So, You Want to Write Some Client-Side Code • vi

• Click HERE to purchase this book now. discuss

Page 9: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

three tools—TypeScript, webpack, and Webpacker—which will be the founda-tion of our application:

• TypeScript1 is an extension of JavaScript that provides type checking andtype inference, which means that TypeScript enforces that values in yourcode have the types that you expect. It’s a superset of JavaScript, whichmeans that any JavaScript program is valid TypeScript, but it also allowsyou to add some basic type checking to your code. More advanced usageallows you to use the type system to prevent invalid states at compile-time and can prevent run-time errors.

• Webpack2 calls itself a “static module bundler,” which I think is prettyjargony, not that anybody asked me. Webpack’s purpose in life is to con-vert developer-friendly inputs to browser-friendly outputs. The inputs arethe code you write—JavaScript, TypeScript, CSS, what have you—allarranged in a hopefully logical structure. Webpack converts all the filesto JavaScript and CSS that the browser can understand, which involvestranslating code and also resolving references to code in different files.The converted HTML and CSS and JS files can then be sent to a browser.

• Webpacker3 is a Rails-specific front end wrapper around webpack. Irealize the similarity in names here is confusing; I’ll try to make it as clearas possible when I’m referring to one tool or the other. The most importantthing Webpacker gives is some Rails-style convention over configurationstructure to your Webpack builds. It also builds in support for commontools, and adds default setups for common frameworks like the ones we’llbe using in this book.

How This Book Is OrganizedThis book is divided into three parts:

In the first part, we’re going to install and start using the tools we need to getRails working with the JavaScript ecosystem. We’ll start with a basic intro-duction to installing the front-end Rails tools. Then we’ll add Stimulus to themix for richer interactions, and then React. Then we’ll augment both tools byshowing some great ways to use CSS tools in our applications. Finally, we’lltake a closer look at our foundation, including the basics of TypeScript,webpack, and Webpacker.

1. https://www.typescriptlang.org2. https://webpack.js.org3. https://github.com/rails/webpacker

• Click HERE to purchase this book now. discuss

How This Book Is Organized • vii

Page 10: Modern Front-End Development for Railsmedia.pragprog.com/titles/nrclient/intro.pdf · The converted HTML and CSS and JS files can then be sent to a browser. • Webpacker3 is a Rails-specific

The second part starts with a deeper look at TypeScript, Webpack, and web-packer, and then covers two very important concerns for front-end code:talking to the server and managing internal state.

The third part goes a little further into TypeScript, showing how we can usethe type system to prevent error conditions. We then talk about debuggingand testing our applications.

By the end of the book, you’ll have options that will show you how to structureyour code for different levels of client-side needs.

There are a lot of ways to do client-side coding, but Rails is here to help. Let’sstart to take a look at the tools it provides.

So, You Want to Write Some Client-Side Code • viii

• Click HERE to purchase this book now. discuss