16,79 €
Improve the development workflow and manage utilities with the latest Webpack and Babel features
Webpack has emerged as one of the most popular module bundlers used in web development projects, and serves as one of the most advanced web development build tools.
This quick reference begins with an introduction to Webpack and teaches you how to use it for initializing dependency management in your web projects. Starting with code splitting and transpiling, you will be taught about dependency graphs and how to configure them to achieve improved functionality and uncover hidden features. You'll also learn the difference between configuration files and options, and how Node.js plays a role in their creation and management. As you advance, you will delve into frameworks and unsupported code, which can be processed using loaders. Moving on, you'll be well on your way to performing application bundling efficiently, and will be introduced to the art of custom loader creation and plugin development.
By the end of this Webpack book, you'll have gained a basic understanding of deployment, live coding, and even hot module replacement, and you'll be able to incorporate application bundling in your web project efficiently.
The book is for web developers looking to get started with dependency management in their web project by learning Webpack. Working knowledge of JavaScript is assumed.
Tom Owens is a seasoned web developer with over 11 years of industry experience. He graduated from Liverpool John Moores University with a BA (Hons), an FdA, and an MSc. His career began as a freelance web designer, granting him experience around numerous new media fields, including game and frontend development. He moved into internet entrepreneurship, having garnered a great deal of knowledge in offering consultancy to highly successful entrepreneurs. He was later offered a role as Lecturer in Web Development for a private institution called SAE, who offer degrees to BSc (Hons) and BA (Hons) students. Tom has an ongoing passion for coaching and mentoring, which he intends to bring to the fore in this book.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 252
Veröffentlichungsjahr: 2020
Copyright © 2020 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.
Commissioning Editor: Pavan RamchandaniAcquisition Editor: Reshma RamanContent Development Editor: Akhil NairSenior Editor: Hayden EdwardsTechnical Editor: Deepesh PatelCopy Editor: Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer: Priyanka DhadkeProduction Designer:Aparna Bhagat
First published: May 2020
Production reference: 1270520
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78995-440-1
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,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
Fully searchable for easy access to vital information
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.packt.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.packt.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.
Tom Owens is a seasoned web developer with over 11 years of industry experience. He graduated from Liverpool John Moores University with a BA (Hons) and an FdA. Later, he would graduate with an MSc from the same institution. His career primarily began as a freelance web designer, which granted him industry experience around numerous related new media fields, including game development and, later, frontend development. He would eventually move into internet entrepreneurship, having garnered a great deal of knowledge in offering consultancy to highly successful individual entrepreneurs. After this, he was offered a role as Lecturer in Web Development for a private institution called SAE, who offered degrees to BSc (Hons) and BA (Hons) students, in partnership with Middlesex University London in the United Kingdom. This would help him cement himself as an expert in his field. He continues to have a passion for coaching and mentoring to this day. He is an active tutor, understanding the benefits of tutoring over lecturing, as it allows the structure to be more fluid, adapting to the bespoke needs of each student. He intends to bring that skill set to the fore in this book.
Sonny Recio is an experienced developer with a seven-year track record of commended performance in software engineering. He recently built his team and solved technical problems on web and mobile apps for his clients.
Nowadays, Sonny spends more time learning and doing frontend development and creates rich user experiences in his projects, aside from managing his team and getting the hang of the business side of things.
He loves using React and is a big fan of functional programming. He reads books related to philosophy, biology, health, art, design, technology, and business in his free time.
Rajat Kumar is an engineer at Netflix, Inc. and has worked with many start-ups and Fortune 100 companies in the last 14 years. He regularly contributes to several open source projects and maintains Restify, an open source framework, built on Node.js.
Rajat enjoys writing code in JavaScript because he believes JavaScript has complexities and imperfections that mimic the real world. Currently, he is driving the architecture behind Netflix's dynamic asset bundling system built on top of webpack.
AaronCzichon is Head of Software Development at Conclurer GmbH, as well as a conference speaker, author, and trainer with a focus on Node.js and web components.
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
Webpack 5 Up and Running
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
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
Conventions used
Get in touch
Reviews
Introduction to Webpack 5
Technical requirements
The fundamentals of Webpack 5
General concepts behind Webpack 5
Terminology
How Webpack works
What's new in Webpack 5? 
Modes
Setting up Webpack
Creating a sample project
Bundling your first project
Summary
Questions
Working with Modules and Code Splitting
Explaining modules
The function of modules
Supported module languages and loaders
Module resolution
Absolute paths
Relative paths
Module paths
Understanding code splitting
Entry points
Preventing duplication with SplitChunksPlugin
Dynamic imports
Caching
Prefetching and preloading modules
Best practices
Bundle analysis
Code linting
Summary
Questions
Further reading
Using Configurations and Options
Understanding configurations
Using different configuration files
Working with options
Understanding asset management
Setting up the project for asset management configurations
Loading CSS files
Loading images
Loading fonts
Loading data
Adding global assets
Wrapping up the tutorial with best practice
Understanding output management 
Output management tutorial preparation
Setting up the HtmlWebpackPlugin
Cleaning up the distribution directory
Utilizing the manifest
Exploring Webpack 5 options
AMD
Bail
Cache
Loader
Profile
Parallelism
Records Path
Records Input Path
Records Output Path
Name
Summary
Questions
APIs, Plugins, and Loaders
Loaders
cache-loader
worker-loader
coffee-loader
coverjs
i18n-loader
imports-loader
polymer-loader
script-loader
source-map-loader
less-loader
APIs
Babel and its loader builder
The Node.js API
Plugins
BabelMinifyWebpackPlugin
CommonsChunkPlugin
ContextReplacementPlugin
HtmlWebpackPlugin
LimitChunkCountPlugin
Summary
Questions
Libraries and Frameworks
Best practices
Working with JSON
Working with YAML
Working with Angular
Working with Vue.js
Summary
Further reading
Questions
Production, Integration, and Federated Modules
Production setup
Shimming
Progressive web applications
Integrating task runners
GitHub
Extracting boilerplate
Module Federation
Building our first federated application
The first application in our system
The second application
The third application
Duplication issues
Summary
Questions
Further reading
Debugging and Migration
Debugging
Hot module replacement
Using DevServer with the Node.js API
HMR and style sheets
Other loaders and frameworks
Adding a utility
Migration
Prerequisites when migrating to version 4 from version 3
Prerequisites when migrating to version 5 from version 4
Enabling persistent caching
Updating Webpack
Summary
Further reading
Questions
Authoring Tutorials and Live Coding Hacks
Authoring libraries
The basic configuration
Using externals to avoid bundling lodash
Specifying external limitations
Exposing the library
Naming the library and working with Node.js
Custom loaders
Setup
Simple usage
Complex usage
Guidelines
Simplifying the purpose of the loader
Utilizing chaining
Modular outputting
Ensuring statelessness
Employing loader utilities
Marking loader dependencies
Resolving module dependencies
Extracting common code
Avoiding absolute paths
Using peer dependencies
Unit testing
Live coding hacks
Monkey Hot Loader
React Hot Patching
Eval
The __Eval hack
Summary
Questions
Assessment
 Answers
Chapter 1: Introduction to Webpack 5
Chapter 2: Working with Modules and Code Splitting
Chapter 3: Using Configurations and Options
Chapter 4: APIs Loaders and Plugins
Chapter 5: Libraries and Frameworks
Chapter 6: Deployment and Installation
Chapter 7: Debugging and Migration
Chapter 8: Authoring Tutorials and Live Coding
Other Books You May Enjoy
Leave a review - let other readers know what you think
When I was asked to write this training book, I realized that very little was known about webpack and its purpose. It is generally something a developer stumbles upon and learns on the job, which can be a very laborious process. There is some documentation on the Webpack.js website as well as a handful of credible resources such as Medium. However, these resources do tend to speak to the reader from the point of view of an expert and I, for one, found this not to be ideal.
Coming from the background of being a lecturer in web development, I have seen how very skilled and intelligent people can have blind spots and knowledge gaps. As a lecturer, I was advised, and also relay the message on, that there are no wrong questions. Many people who have not come from a teaching background might suggest they don't want to speak down to you and would prefer you not ask the wrong questions. We have found this is harmful if a student would rather remain silent over asking questions.
I intend to keep things as simple as possible. I may have failed already using words such as "bespoke", nonetheless, the premise is that all of us have head-slapping moments, where we should have done something, and later on realize what we did wrong. Am I right? Well, it happens to the most brilliant of us. Also, most instructors may be reluctant to talk you through something to the nth degree for fear of patronizing you. The problem being is that there will always be some mundane detail, that the developer thought obvious but could be interpreted more than one way. When I lectured the rule was: "there are no stupid questions", so I hope to prove the necessity of that theory.
The book is for web developers who wish to get started with dependency management in their web project by learning Webpack. Working knowledge of JavaScript is assumed.
Chapter 1, Introduction to Webpack 5, will introduce you to Webpack—specifically, Webpack version 5. It will include an overview of the central concepts around Webpack and how it is used.
Chapter 2, Working with Modules and Code Splitting, will elaborate on modules and code splitting, as well as some of the more salient and interesting aspects of Webpack 5 that are key to understanding Webpack.
Chapter 3, Using Configurations and Options, will look at the world of configuration, understanding its limitations and capabilities as well as where options can play their part.
Chapter 4, APIs, Plugins, and Loaders, will pry into the world of APIs, loaders, and plugins. These features of Webpack expound the capabilities of the platform, springboarding from configurations and options.
Chapter 5, Libraries and Frameworks, will discuss libraries and frameworks. Our examination of plugins, APIs, and loaders has revealed that sometimes, we don't want to use remote code such as libraries, but other times we do. Webpack generally deals with locally hosted code, but there are times when we might want to work with libraries. This provides a good transition to that topic.
Chapter 6, Production, Integration, and Federated Modules, will provide an in-depth account of this subject and will hopefully address any concerns you might have as a developer.
Chapter 7, Debugging and Migration, will discuss hot module replacement and live coding, and get to grips with some serious tutorials.
Chapter 8, Authoring Tutorials and Live Coding Hacks, will show you working examples of very simple, easy-to-apply, but bespoke practical lessons in Webpack 5, specifically Webpack 5 over earlier versions. There will be vanilla JavaScript tutorials as well as common frameworks, Vue.js will be a good one.
You can find the code used in all of the chapters in this book at https://github.com/PacktPublishing/Webpack-5-Up-and-Running. To get the most out of this book, you will need the following:
Fundamental knowledge of JavaScript.
Ensure that you have the latest version of Webpack 5 installed.
You will need the use of a command-line interface, such as Command Prompt or another command-line utility of your choice.
You will need Node.js,
the JavaScript runtime environment.
Ensure that you've installed the latest version of Node.js (webpack 5 requires at least Node.js 10.13.0 (LTS)); otherwise, y
ou may encounter a lot of issues.
You will need
npm
installed on your local machine with administrator-level privileges.
Webpack and Webpack 5 run in the Node.js environment, which is why we need its package manager—NPM.
As of the time of writing, the most current release is Webpack version 5. Visit
https://webpack.js.org
to find the most current version for you.
You can download the example code files for this book from your account at www.packt.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.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
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 athttps://github.com/PacktPublishing/Webpack-5-Up-and-Running. 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!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The following lines are a code snippet from the package.json file."
A block of code is set as follows:
"scripts": {
"build": "webpack --config webpack.config.js"
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<!doctype html><html> <head> <title>Webpack - Test</title>
<script src="https://unpkg.com/[email protected]">
</script> </head> <body> <script src="./src/index.js"></script> </body></html>
Any command-line input or output is written as follows:
npm install --save-dev webpack-cli
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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/support/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 packt.com.
This book is aimed at experienced JavaScript developers,designed to take you through the development and production of a specific example project through step-by-step processes. By the time you get to the end of this guide, you should be able to fully set up and deploy a working bundled application.
This chapter will introduce you to Webpack—specifically, Webpack version 5. It will include an overview of the central concepts around Webpack and how it is used.
This chapter is aimed at programmers who are new to Webpack and Webpack 5. The initial setup will be covered in this chapter, as well as an overview of the process, and you will be shown how to deploy your first bundled application.
The following topics will be covered in this chapter:
The fundamentals of Webpack 5
Setting up Webpack
Creating a sample project
You can find the code used in all of the chapters in this book at https://github.com/PacktPublishing/Webpack-5-Up-and-Running:
To use this guide, you will need a fundamental knowledge of JavaScript.
Ensure that you have the latest version of Webpack 5 installed.
You will need the use of a command line, such as Command Prompt or another command-line utility of your choice.
You will need Node.js,
the JavaScript runtime environment.
Ensure that you've installed the latest version of
Node.js;
otherwise, y
ou may encounter a lot of issues.
You will need
npm
installed on your local machine with administrator-level privileges.
Webpack and Webpack 5 run in the Node.js environment, which is why we need its package manager—npm.
As of the time of writing, the most current release is Webpack version 5. Visit
https://webpack.js.org
to find the most current version for you.
Essentially, Webpack is a module bundler for JavaScript applications. Webpack takes a series of JavaScript files, along with dependencies such as image files, which make up an application, and constructs something called a dependency graph. A dependency graph is a representation of how these files and dependencies are ordered and linked within an application and shows how the files interact with each other.
This dependency graph then forms a template that the bundler follows when taking all of the dependencies and files to compress them into a smaller set. Webpack is then able to bundle these files into a larger, but usually less-numerous, set of files. This eliminates problems such as unused code, repetitive code, and the need for rewriting. To some extent, the code can be formatted more succinctly.
Webpack recursively builds every module in your application, then packs all those modules into a small number of bundles. For the most part, a bundled application will contain a script that is ideal to be read by a program, such as a web browser, but too complicated for a programmer to use. The developer, therefore, will take a set of source files and make changes to this area of the program, then bundle this source into an output—a bundled application.
Bundling was originally intended to improve browser-reading performance, but it also has many other advantages. Once a set of source files is bundled by Webpack, it will usually follow a systematic and conventional filing structure. Errors within the code can halt a bundling operation; this book will instruct you on how to overcome these problems.
Now, let's explore the general concepts around Webpack 5.
Here, we will begin to understand the key concepts and the purpose of Webpack, rather than expect you to have any prior understanding of it. Bundling is carried out locally on a desktop using Node.js or npm and the command-line interface (CLI), usually Command Prompt.
Webpack is a build tool that puts all of your assets into a dependency graph. This includes JavaScript files, images, fonts, and Cascading Style Sheets (CSS). It will take Sassy CSS (SCSS) and TypeScript files and place them into CSS and JavaScript files, respectively. Webpack will only be able to do this when the code is compatible with the latter format.
When programming in JavaScript and other languages, the source code will often use a statement such as require(), which points one file to another. Webpack will detect this statement and determine the file that is needed as a dependency. This will decide how the files are processed in your final JavaScript bundle. This will also include replacing a URL path to a content delivery network (CDN)—which is, essentially, a network of proxy servers—with a local file.
The following diagram is a representation of the general purpose of Webpack, which is to take a set of files or dependencies and output the content in an optimized form:
Now, let's take a closer look at some of the terminology, which you may be unfamiliar with but can be considered common parlance when using Webpack.
This section will cover the terminology used in Webpack 5. This will include native terms, as well as some more unusual acronyms:
Assets
: This is a term frequently used in Webpack to prevent conflations of concepts. It refers to image files, or even data or script files, collated by the software when producing a bundled application.
Bundle:
This refers to the application that is output once Webpack has compiled an application. This is an optimized version of the original or source application—the reasons for this will be discussed in detail in later chapters. The bundler will combine these files into one file, which makes unpicking and hacking very difficult. It also improves browser performance. It does this by ensuring that processors are kept to an optimal level and removing any coding structure that does not conform to a standard. This also encourages the developer to adopt conventions a lot more diligently. Should there be any insecure programming, these locations are more easily identified, isolated, and corrected.
SASS:
A version of
CSS
that has enhanced features. Webpack handles this code as it does CSS; however, it is a phrase that may come up and leave you stumped, so it is worth knowing about.
SCSS:
This is simply the name for the syntax version used to give SASS extra functionality. It is useful to know that Webpack is capable of transpiling both syntaxes.
Transpiling
: This
is the process where Webpack 5 takes a set of input source code and changes it into a more optimized output distribution code. This is done by removing unused or duplicated code. Transpiling is used to convert one set of files into a simpler set. For instance, SCSS often contains script that can be easily stored inside a CSS file. You might also transpile SCSS to CSS, or TypeScript to JavaScript.
TypeScript
:
For the uninitiated,
TypeScript
is a type of code that is similar to JavaScript in many ways. Browsers, for instance, most commonly run JavaScript, so it may be more appropriate to use JavaScript, where possible. Webpack 5 will transpile TypeScript into JavaScript whenever the former allows.
CDN:
A CDN is a network of proxy servers that provides high availability and high performance. Some examples are Google APIs, such as Google Fonts, and other similar tools that all JavaScript developers are, no doubt, familiar with.
Dependency graphs
:
In
Webpack 5, a
dependency graph
is a directed graph representing the dependency of several assets to each other. Webpack 5
maps a list of assets and dependencies itself and records how they depend on each other in an application. It uses this to derive an appropriate output file structure.
Though JavaScript is the entry point, Webpack appreciates that your other asset types—such as HTML, CSS, and SVG—each have dependencies of their own, which should be considered as part of the build process.
Webpack is comprised of input and output. The output can be made of one or more files. As well as bundling modules, Webpack can carry out a lot of functions on your files. The input refers to the original files when they are in their original structure, before bundling. The output refers to the resulting bundled files in their new and optimized filing structure. Inputs, therefore, are comprised of the source files and outputs can be comprised of development files or production files.
There is often a conflation between the terms input and output and source code and development code.
When working with Webpack 5, these phrases may present themselves and it is important that you don't get too confused by them.
That summarizes the bulk of the terminology you will come across when using Webpack. Now, we will explore how the software works.
Webpack works by generating a dependency graph of assets in a set of source files, which it transpiles an optimized set of distribution files from. These source and distribution files contain source code and distribution code, respectively. This distributed code forms the output. Distribution is simply another name for the output or bundle.
Webpack begins by finding an entry point in the source files and from there, it builds a dependency graph. The selection of an entry point is optional in Webpack 5 and the choice of selection will alter the nature of the build process, either in terms of speed or output optimization.
Webpack 5 is capable of transforming, bundling, or packaging just about any resource or asset.
We have covered a good overview of how the software works; experienced users of previous Webpack versions may consider this overview rudimentary, so let's have a look at what is new in this current version.
The popular Webpack module bundler has undergone a massive update for the release of version 5. Webpack 5 offers massive performance improvements, more dynamic scalability, and basic backward compatibility.
Webpack 5 takes over from version 4, where backward compatibility wasn't always possible with many of the various loaders available, which were often more compatible with version 2, which meant that a developer would often encounter deprecation warnings in the command line if version 2 wasn't used. Webpack 5 has now addressed this issue.
Another big selling point of version 5 is federated modules. We will discuss this in more detail in a later Chapter 6, Production, Integration, and Federated Modules. However, to sum it up, federated modules are essentially a way for a bundled application to utilize and interact with modules and assets in remotely stored separate bundles.
The advantages of Webpack 5 are summarized as follows:
Webpack 5 offers control over HTTP requests, which improves speed and performance, and also alleviates security concerns.
Webpack 5 has some advantages over rival bundlers such as Browserify and systemjs—namely, speed. The build time directly depends on the configuration but it's faster than its nearest rivals.
Little or no configuration is required to use Webpack 5, but you always have it as an option.
