Learning JavaScript Design Patterns: A JavaScript and React Developer’s Guide, 2nd Edition / Изучение шаблонов проектирования на JavaScript: Руководство для разработчиков JavaScript и React, 2-е издание
Год издания: 2023
Автор: Osmani Addy / Османи Эдди
Издательство: O’Reilly
ISBN: 9781098139872
Язык: Английский
Формат: PDF, EPUB
Качество: Издательский макет или текст (eBook)
Количество страниц: 299
Описание: Do you want to write beautiful, structured, and maintainable JavaScript by applying modern design patterns to the language? Do you want clean, efficient, manageable code? Want to stay up-to-date with the latest best practices? If so, the updated second edition of Learning JavaScript Design Patterns is the ideal place to start.
Author Addy Osmani shows you how to apply modern design patterns to JavaScript and React. That includes popular design patterns such as modules, mixins, observers, and mediators. You’ll learn about performance and rendering patterns, such as server-side rendering and islands architecture. You’ll also learn how modern architectural patterns—such as MVC, MVP, and MVVM—are useful from the perspective of a modern web application developer. Other essential topics include modern JavaScript syntax and React patterns such as Hooks, higher order components, and render props.
This book explores:
Patterns to architect your components and apps
More than 20 design patterns in JavaScript and React
Different pattern categories, including creational, structural, and behavioral
Performance patterns such as dynamic imports and code-splitting
Rendering patterns such as server-side rendering, hydration, islands architecture, and more
Вы хотите написать красивый, структурированный и поддерживаемый JavaScript, применяя к языку современные шаблоны проектирования? Вам нужен чистый, эффективный, управляемый код? Хотите быть в курсе последних передовых практик? Если это так, то обновленное второе издание Learning JavaScript Design Patterns - идеальное место для начала.
Автор Эдди Османи показывает вам, как применять современные шаблоны проектирования к JavaScript и React. Это включает в себя популярные шаблоны проектирования, такие как модули, микcины, наблюдатели и посредники. Вы узнаете о производительности и шаблонах рендеринга, таких как рендеринг на стороне сервера и архитектура islands. Вы также узнаете, насколько современные архитектурные шаблоны, такие как MVC, MVP и MVVM, полезны с точки зрения современного разработчика веб—приложений. Другие важные темы включают современный синтаксис JavaScript и шаблоны React, такие как хуки, компоненты более высокого порядка и реквизиты для рендеринга.
В этой книге исследуется:
Шаблоны для создания ваших компонентов и приложений
Более 20 шаблонов проектирования в JavaScript и React
Различные категории паттернов, включая творческие, структурные и поведенческие
Шаблоны производительности, такие как динамический импорт и разделение кода
Шаблоны рендеринга, такие как рендеринг на стороне сервера, гидратация, архитектура islands и многое другое
Код на
GitHub
Внимание! Торрент перезалит. Просьба перекачать файл.
Причина: Замена PDF.
Оглавление
Preface xi
1. Introduction to Design Patterns1
History of Design Patterns 2
What Is a Pattern? 2
An Everyday Use Case for Design Patterns 4
Summary 5
2. “Pattern”-ity Testing, Proto-Patterns, and the Rule of Three 7
What Are Proto-Patterns? 7
The “Pattern” Tests 8
Rule of Three 9
Summary 9
3. Structuring and Writing Patterns 11
The Structure of a Design Pattern 11
Well-Written Patterns 12
Writing a Pattern 13
Summary 14
4. Anti-Patterns 15
What Are Anti-Patterns? 15
Anti-Patterns in JavaScript 16
Summary 17
5. Modern JavaScript Syntax and Features 19
The Importance of Decoupling Applications 19
Modules with Imports and Exports 20
Module Objects 22
Modules Loaded from Remote Sources 23
Static Imports 23
Dynamic Imports 23
Import on Interaction 24
Import on Visibility 24
Modules for the Server 24
Advantages of Using Modules 25
Classes with Constructors, Getters, and Setters 26
Classes in JavaScript Frameworks 28
Summary 29
Related Reading 29
6. Categories of Design Patterns 31
Background 31
Creational Design Patterns 32
Structural Design Patterns 32
Behavioral Design Patterns 32
Design Pattern Classes 32
Summary 34
7. JavaScript Design Patterns 35
Creational Patterns 35
The Constructor Pattern 36
Object Creation 36
Basic Constructors 38
Constructors with Prototypes 39
The Module Pattern 40
Object Literals 40
The Module Pattern 42
Module Pattern Variations 46
Modern Module Pattern with WeakMap 48
Modules with Modern Libraries 50
The Revealing Module Pattern 51
Advantages 53
Disadvantages 53
The Singleton Pattern 53
State Management in React 57
The Prototype Pattern 58
The Factory Pattern 61
When to Use the Factory Pattern 64
When Not to Use the Factory Pattern 64
Abstract Factories 64
Structural Patterns 65
The Facade Pattern 66
The Mixin Pattern 68
Subclassing 68
Mixins 69
Advantages and Disadvantages 72
The Decorator Pattern 73
Pseudoclassical Decorators 76
Interfaces 77
Abstract Decorators 78
Advantages and Disadvantages 81
Flyweight 82
Using Flyweights 83
Flyweights and Sharing Data 83
Implementing Classical Flyweights 83
Converting Code to Use the Flyweight Pattern 86
A Basic Factory 89
Managing the Extrinsic States 89
The Flyweight Pattern and the DOM 91
Example: Centralized Event Handling 91
Behavioral Patterns 93
The Observer Pattern 93
Differences Between the Observer and Publish/Subscribe Pattern 97
Advantages 100
Disadvantages 100
Publish/Subscribe Implementations 100
The Mediator Pattern 110
A Simple Mediator 111
Similarities and Differences 112
Event Aggregator Use 114
Mediator Use 114
Event Aggregator (Pub/Sub) and Mediator Together 115
Mediator/Middleware in Modern JavaScript 116
Mediator Versus Facade 117
The Command Pattern 117
Summary 119
8. JavaScript MV* Patterns 121
MVC 121
Smalltalk-80 MVC 122
MVC for JavaScript Developers 122
Models 123
Views 124
Templating 126
Controllers 128
What Does MVC Give Us? 128
Smalltalk-80 MVC in JavaScript 128
Summary of MVC 129
MVP 129
Models, Views, and Presenters 130
MVP or MVC? 131
MVVM 132
History 132
Model 133
View 133
ViewModel 134
Recap: The View and the ViewModel 134
ViewModel Versus Model 134
Pros and Cons 135
Advantages 135
Disadvantages 135
MVC Versus MVP Versus MVVM 135
Modern MV* Patterns 136
MV* and React.js 136
Summary 137
9. Asynchronous Programming Patterns 139
Asynchronous Programming 139
Background 141
Promise Patterns 142
Promise Chaining 143
Promise Error Handling 144
Promise Parallelism 144
Promise Sequential Execution 144
Promise Memoization 144
Promise Pipeline 145
Promise Retry 146
Promise Decorator 146
Promise Race 147
async/await Patterns 147
async Function Composition 147
async Iteration 148
async Error Handling 148
async Parallelism 148
async Sequential Execution 149
async Memoization 149
async Event Handling 149
async/await Pipeline 150
async Retry 150
async/await Decorator 150
Additional Practical Examples 151
Making an HTTP Request 151
Reading a File from the Filesystem 151
Writing to a File on the Filesystem 151
Executing Multiple async Operations 152
Executing Multiple async Operations in Sequence 152
Caching the Result of an async Operation 152
Handling Events with async/await 153
Retrying an async Operation on Failure 153
Creating an async/await Decorator 153
Summary 154
10. Modular JavaScript Design Patterns 155
A Note on Script Loaders 155
AMD 156
Getting Started with Modules 156
AMD Modules with jQuery 160
AMD Conclusions 163
CommonJS 163
Getting Started 164
Consuming Multiple Dependencies 165
CommonJS in Node.js 166
Is CommonJS Suitable for the Browser? 166
Related Reading for CommonJS 167
AMD and CommonJS: Competing, but Equally Valid Standards 167
UMD: AMD and CommonJS-Compatible Modules for Plug-ins 168
Summary 173
11. Namespacing Patterns 175
Namespacing Fundamentals 175
Single Global Variables 176
Prefix Namespacing 176
Object Literal Notation 177
Nested Namespacing 180
Immediately Invoked Function Expressions 181
Namespace Injection 184
Advanced Namespacing Patterns 186
Automating Nested Namespacing 186
Dependency Declaration Pattern 188
Deep Object Extension 189
Recommendation 191
Summary 192
12. React.js Design Patterns 193
An Introduction to React 193
Terminology Used 194
Basic Concepts 194
Higher-Order Components 196
Composing 199
Pros 199
Cons 200
Render Props Pattern 200
Lifting State 202
Children as a Function 204
Pros 205
Cons 205
Hooks Pattern 205
Class Components 206
Restructuring 207
Complexity 208
Hooks 208
State Hook 208
Effect Hook 210
Custom Hooks 211
Additional Hooks Guidance 213
Pros and Cons of Using Hooks 213
React Hooks Versus Classes 216
Static Import 216
Dynamic Import 217
Loadable Components 219
Import on Interaction 220
Import on Visibility 220
Code-Splitting 221
Route-based Splitting 221
Bundle Splitting 222
PRPL Pattern 224
Loading Prioritization 226
Preload in Single-Page Apps 227
Preload + the async Hack 228
Preload in Chrome 95+ 228
List Virtualization 228
How Does Windowing/Virtualization Work? 228
Lists 229
Grid 230
Improvements in the Web Platform 232
Conclusions 232
Summary 232
13. Rendering Patterns 233
Importance of Rendering Patterns 234
Client-Side Rendering 236
Server-Side Rendering 236
Static Rendering 237
Incremental Static Regeneration 238
On-Demand ISR 239
Summary of Static Rendering 239
Streaming SSR 240
Edge SSR 241
Hybrid Rendering 241
Progressive Hydration 242
Islands Architecture 243
Implementing Islands 243
Pros and Cons 244
React Server Components 245
Hybrid Rendering with RSC and the Next.js App Router 246
Summary 246
14. Application Structure for React.js 249
Introduction 249
Group by Module, Feature, or Route 250
Group by File Type 250
Hybrid Grouping Based on Domain and Common Components 251
Application Structure for Modern React Features 252
Redux 253
Containers 253
Hooks 253
Styled Components 254
Other Best Practices 254
Application Structure for Next.js Apps 256
Summary 257
15. Conclusions 259
Appendix: References 261
Index 263