Module Bundlers Explained... Webpack, Rollup, Parcel, and Snowpack

Fireship · Beginner ·🌐 Frontend Engineering ·5y ago

Key Takeaways

The video explains the concept of module bundlers, specifically Webpack, Rollup, Parcel, and Snowpack, and how they can be used to package code as a production-ready web application. It covers the installation, configuration, and usage of these tools, as well as their features and benefits.

Full Transcript

to build a website you only need three ingredients html css and javascript that sounds pretty straightforward on the surface but here's the problem nobody just uses html css and javascript to build a website you might replace javascript with typescript then throw in a ui library like react to replace html you'll definitely need a css preprocessor like sas then you'll need to import a whole bunch of third-party modules so you're not doing everything from scratch many of your dependencies might use common js which isn't going to work with your modern es module syntax the code will have name collisions all over the place and even if you do manage to get it to work you'll likely end up with a massive javascript file which then needs to be minified and broken into smaller chunks just so people can visit your site with a reasonable load time you'll also need to create different versions of your javascript and load polyfills to ensure that your code works on legacy browsers as a developer it's like being asked to land on the moon with a lawn chair and some balloons tied to it it's truly the most annoying aspect of building a web application but thankfully we have module bundlers which make this entire process a little less annoying in today's video you'll learn everything you ever wanted to know about module bundlers like webpack roll up parcel and snowpack we'll primarily focus on webpack because it's the most popular but most of the core concepts that we'll look at apply to all of them but make sure to watch until the end when we look at snowpack because it uses a technique that is much different than the others and represents what i think will be the future of front end web development if you're new here like and subscribe and consider becoming a pro member at fireship io or sponsor me on github for even more content let's start by answering the question of what is a module bundler i already presented a long list of problems and the role of the module bundler is to fix these problems the most fundamental thing they do is take multiple javascript files and combine them into a single large file that can be then used in the browser to load your javascript app this file or the javascript bundle as it's called contains your source code along with any third-party dependencies that you've imported your dependencies also likely have their own dependencies that need to be imported a bundler like webpack creates a dependency graph to keep track of how to put everything together you just tell webpack where to find your entry point and it will look at all of your imports and dependencies and try to piece everything together into that single file the best way to really learn how this process works is to do it yourself go ahead and open up vs code and we'll do everything step by step so you can follow along with this video from an empty directory create an index.js file in the source directory now currently this file doesn't have any dependencies so there's no need for a module bundler we could simply run this file with node or directly in the browser things get more complicated when we add dependencies like those from node package manager run the command npm init flag y to create a package.json file now let's install the world's most dependent on javascript library lowdash when we run npm install it adds node modules here to the root directory and then adds lowdash to the dependencies object in the package.json now what we want to build here is a frontend web application so i'll create a public directory and inside that directory add an index.html file i'll add some initial html boilerplate then in the head of the document add a script tag that references our index.js file now currently our javascript code isn't using lowdash or any dependencies yet if we view this file in the browser you can see we get our hello world console logged here without any errors but now let's go back to our code and see what happens when we try to use a dependency from lowdash we'll go ahead and import the camelcase function and then camelcase our console.log now let's go back to the browser and try to view our website you'll notice we get an error in the console the reason we get this error is because the browser doesn't know how to resolve the low dash code in other words you're asking it to find something but it has no idea where to find it and that's where something like webpack can help us out to use it we first need to install it as a development dependency we'll install the webpack cli along with webpack itself now most often when you bundle your production code you'll use a script here in the package.json file we'll give the script a name of build and it simply calls the webpack command at this point we can execute our script and run webpack by entering npm run build from the command line webpack will analyze the code in our index.js file and then compile it to a dist main.js file which is our production code or the code that we would ship to the end user in the browser so with that being said let's go into our index.html file and we'll change the path in our script tag to point to the main.js file if we reload the browser the error should be gone and we should see hello world in camelcase congratulations you just bundled your first module it's important to note that we're currently using the default webpack config and by default it looks for the source index.js file if your files name something else it won't work in most cases though you'll want or need to customize the behavior of webpack in which case you can create a webpack config file the file itself is a javascript module that exports an object that customizes the behavior of webpack let's take a look at some of the most important parts of the object so you're not totally confused if you're the unfortunate developer who has to modify the webpack config the first attribute is entry which defines the entry point to your application in our case that's the index.js file in the source directory it's also worth noting that entry can be an object to support multiple entry points you might see this used to support a technique called code splitting so they're only loaded on the pages that actually need that code it's beyond the scope of this video but it's just good to know what code splitting means from there we have output which is the name of the file that we want to compile our javascript to by default it's main.js but we may want to change it to something else and when determining the file location we can use node.js utilities like path to resolve a consistent path name now if we go ahead and run the build command again you'll notice it outputs our bundle to a file called awesome.js that's pretty straightforward but you often have more to worry about than just javascript when building a full web application let's make things a little more interesting by adding an scss file to our code not only is this file not javascript but it also needs to be compiled by the sas compiler we can make the file known to webpack by importing it in our index.js file but when we try to compile our code you'll notice we get an error that says module parse failed currently no loaders are configured to process this file but what is a loader exactly in webpack a loader is a way to pre-process a file in our case we want to import some css code then tell our javascript to inject that css in the dom when our web application is loaded essentially loaders provide a way to handle any kind of file that's not plain javascript loaders exist for pretty much every use case you can imagine including typescript markdown and various css preprocessors in our case we're going to use three different loaders style loader css loader and sas loader we can install these packages in our development environment then we'll go back to our webpack config then add the module attribute in this section we can add one or more rules that will match a certain file type to the required loaders the rule itself will have a test attribute that is a regular expression that matches any file that ends in scss when webpack encounters one of these files it can use the following loaders to process the scss into regular css and then to javascript so it can eventually be injected into an html page let's go ahead and save the config and then run our build command again when we open the output main.js we can search through it and we'll find our css code embedded here loaders will likely do most of the heavy lifting for you in webpack but you can also tap into the webpack compiler directly using its plugin system a plugin allows you to tap into the entire compilation lifecycle we're not going to build a plug-in from scratch in this video but we'll look at how to use one of my favorite open source plugins the webpack bundle analyzer we can install it with npm and it will tell us exactly how big our javascript bundle is and which dependencies are contributing to its size in our webpack config we'll first import the bundle analyzer plugin then we'll go down and create a plugins array and instantiate the plugin there now if we run the build command again it will bring up this visualization of our javascript bundle as you can see here loadash is taking up the majority of the space and we can optimize that by only installing the actual functions from lodash that we really need for the app now one annoying thing that we've been doing at this point is running the npm build command every time we make a change another way bundlers help you out is by setting up a local dev server to watch changes to your project and recompile them so you don't have to do it manually first we'll use npm to install webpack dev server then we'll go into our webpack config and use the dev server option to configure the files that we want to serve and the port that they should be served on you can also configure the server for compression and hot module replacement in any case we likely want to add another npm script at this point we'll go ahead and give it a name of dev and it will run the webpack serve command if we go ahead and run that script with npm run dev you'll notice it loads up a server on localhost 9000 and it will also watch the source directory for any changes and recompile anytime we save a file so hopefully that gives you enough to get started with webpack without feeling overwhelmed other popular module bundlers like rollup and parcel are very similar to webpack but try to achieve the same result with less configuration those are definitely tools you should be aware of but what i want to focus on next is a relatively new bundler called snowpack one thing you might have noticed when we were using webpack is that it took a while to compile all of our code each file change would take about four seconds to compile our css and javascript into a new bundle and it can be a super annoying waste of time especially on larger projects snowpack takes a different approach to handling modules and development instead of recompiling on every change it builds all of your dependencies once and then ships them directly to the browser that means when you make a change to your javascript code it can be reflected in the browser instantly snowpack only needs to rebuild one file instead of going through the entire dependency graph this is really awesome when you have a big complex project because as your project grows bigger your build times don't they stay consistently fast i've been using it for a personal project of mine and the developer experience has been awesome so i'd highly recommend checking it out for your next project i'm going to go ahead and wrap things up there if this video helped you please like and subscribe and consider becoming a pro member at fireship io for more advanced content thanks for watching and i will see you in the next one

Original Description

What is a Module Bundler? And why do I need one? Learn how tools like Webpack, Rollup, Parcel, and Snowpack can package your code as a production-ready web application. https://fireship.io Webpack https://webpack.js.org/ Snowpack https://www.snowpack.dev/ Sponsor me for $1 https://github.com/codediodeio #webdev #tutorial #javascript Install the quiz app 🤓 iOS https://itunes.apple.com/us/app/fireship/id1462592372?mt=8 Android https://play.google.com/store/apps/details?id=io.fireship.quizapp Upgrade to Fireship PRO at https://fireship.io/pro Use code lORhwXd2 for 25% off your first payment. My VS Code Theme - Atom One Dark - vscode-icons - Fira Code Font
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Fireship · Fireship · 0 of 60

← Previous Next →
1 Angular 4 Development and Production Environments with Firebase
Angular 4 Development and Production Environments with Firebase
Fireship
2 OAuth with Angular and Firebase Tutorial
OAuth with Angular and Firebase Tutorial
Fireship
3 Anonymous Authentication with Angular and Firebase - Lazy Registration
Anonymous Authentication with Angular and Firebase - Lazy Registration
Fireship
4 Angular Router Guards for Firebase Users
Angular Router Guards for Firebase Users
Fireship
5 Angular Firebase CRUD App with NoSQL Database Tutorial
Angular Firebase CRUD App with NoSQL Database Tutorial
Fireship
6 Upload Files from Angular to Firebase Storage
Upload Files from Angular to Firebase Storage
Fireship
7 How to Deploy an Angular App to Firebase Hosting
How to Deploy an Angular App to Firebase Hosting
Fireship
8 Sharing Data between Components in Angular
Sharing Data between Components in Angular
Fireship
9 Loading Spinners for Asynchronous Firebase Data
Loading Spinners for Asynchronous Firebase Data
Fireship
10 Angular 4 Transactional Email with Google Firebase Cloud Functions
Angular 4 Transactional Email with Google Firebase Cloud Functions
Fireship
11 Firebase Database Rules Tutorial
Firebase Database Rules Tutorial
Fireship
12 Autocomplete Search with Angular4 and Firebase
Autocomplete Search with Angular4 and Firebase
Fireship
13 Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Reddit Inspired Upvoting System with Angular and Firebase NoSQL
Fireship
14 Angular Drag-and-Drop File Uploads to Firebase Storage
Angular Drag-and-Drop File Uploads to Firebase Storage
Fireship
15 Text Translation with Firebase Cloud Functions onWrite and Angular 4
Text Translation with Firebase Cloud Functions onWrite and Angular 4
Fireship
16 Custom Usernames with Firebase Authentication
Custom Usernames with Firebase Authentication
Fireship
17 Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Twitter-Inspired Follow Unfollow Feature with Firebase and Angular 4
Fireship
18 Simple Pagination with Firebase and Angular 4
Simple Pagination with Firebase and Angular 4
Fireship
19 How to Connect Firebase Users to their Data - 3 Methods
How to Connect Firebase Users to their Data - 3 Methods
Fireship
20 Add Toast Message Notifications to your Angular App
Add Toast Message Notifications to your Angular App
Fireship
21 Facebook-Inspired Reactions System with Angular and Firebase
Facebook-Inspired Reactions System with Angular and Firebase
Fireship
22 Learn NgModule in Angular with Examples
Learn NgModule in Angular with Examples
Fireship
23 Lazy Loading Components in Angular 4
Lazy Loading Components in Angular 4
Fireship
24 Stripe Checkout Payments with Angular and Firebase - Part 1
Stripe Checkout Payments with Angular and Firebase - Part 1
Fireship
25 Process Stripe Payments with Firebase Cloud Functions - Part 2
Process Stripe Payments with Firebase Cloud Functions - Part 2
Fireship
26 Selling Digital Content in Angular with Stripe Payments - Part 3
Selling Digital Content in Angular with Stripe Payments - Part 3
Fireship
27 Angular 4 Full Text Search with Algolia - Part 1
Angular 4 Full Text Search with Algolia - Part 1
Fireship
28 Algolia with Firebase Cloud Functions - Part 2
Algolia with Firebase Cloud Functions - Part 2
Fireship
29 Firebase Phone Authentication in Angular 4
Firebase Phone Authentication in Angular 4
Fireship
30 Top 7 RxJS Concepts for Angular Developers
Top 7 RxJS Concepts for Angular Developers
Fireship
31 Learn Angular Animations with 5 Examples
Learn Angular Animations with 5 Examples
Fireship
32 Advanced Firebase Data Filtering (Multi-Property)
Advanced Firebase Data Filtering (Multi-Property)
Fireship
33 Realtime Maps with Mapbox + Firebase + Angular
Realtime Maps with Mapbox + Firebase + Angular
Fireship
34 Angular Reactive Forms with Firebase Database Backend
Angular Reactive Forms with Firebase Database Backend
Fireship
35 Send Push Notifications in Angular with Firebase Cloud Messaging
Send Push Notifications in Angular with Firebase Cloud Messaging
Fireship
36 Top 7 Ways to Debug Angular 4 Apps
Top 7 Ways to Debug Angular 4 Apps
Fireship
37 Infinite Scroll with Angular and Firebase
Infinite Scroll with Angular and Firebase
Fireship
38 Use TypeScript with Firebase Cloud Functions
Use TypeScript with Firebase Cloud Functions
Fireship
39 Realtime Graphs and Charts with Plotly and Firebase
Realtime Graphs and Charts with Plotly and Firebase
Fireship
40 Role-Based User Permissions in Firebase
Role-Based User Permissions in Firebase
Fireship
41 User Presence System in Realtime - Online, Offline, Away
User Presence System in Realtime - Online, Offline, Away
Fireship
42 Location-based Queries with GeoFire and Angular Google Maps
Location-based Queries with GeoFire and Angular Google Maps
Fireship
43 Angular ngrx Redux Quick Start Tutorial
Angular ngrx Redux Quick Start Tutorial
Fireship
44 Angular Ngrx Effects with Firebase Database
Angular Ngrx Effects with Firebase Database
Fireship
45 Progressive Web Apps with Angular
Progressive Web Apps with Angular
Fireship
46 Angular Ngrx with Firebase Google OAuth User Authentication
Angular Ngrx with Firebase Google OAuth User Authentication
Fireship
47 RxJS Quick Start with Practical Examples
RxJS Quick Start with Practical Examples
Fireship
48 Send SMS Text Messages with Twilio and Firebase
Send SMS Text Messages with Twilio and Firebase
Fireship
49 Firebase Database Performance Profiling
Firebase Database Performance Profiling
Fireship
50 Native Desktop Apps with Angular and Electron
Native Desktop Apps with Angular and Electron
Fireship
51 Subscription Payments with Stripe, Angular, and Firebase
Subscription Payments with Stripe, Angular, and Firebase
Fireship
52 Firestore with AngularFire5 Quick Start Tutorial
Firestore with AngularFire5 Quick Start Tutorial
Fireship
53 Angular HTTP Client Quick Start Tutorial
Angular HTTP Client Quick Start Tutorial
Fireship
54 Google Sign-In with Firestore Custom User Data
Google Sign-In with Firestore Custom User Data
Fireship
55 Star Review System from Scratch with Firestore + Angular
Star Review System from Scratch with Firestore + Angular
Fireship
56 Angular Chatbot with Dialogflow (API.ai)
Angular Chatbot with Dialogflow (API.ai)
Fireship
57 Learn @ngrx/entity and Feature Modules
Learn @ngrx/entity and Feature Modules
Fireship
58 Infinite Scroll Pagination with Firestore
Infinite Scroll Pagination with Firestore
Fireship
59 Faster Firestore via Data Aggregation
Faster Firestore via Data Aggregation
Fireship
60 Contentful - CMS for Angular Progressive Web Apps
Contentful - CMS for Angular Progressive Web Apps
Fireship

This video teaches the basics of module bundlers, specifically Webpack, Rollup, Parcel, and Snowpack, and how to use them to package code as a production-ready web application. It covers the installation, configuration, and usage of these tools, as well as their features and benefits. By the end of this video, viewers will be able to build and configure their own web applications using module bundlers.

Key Takeaways
  1. Install Webpack as a development dependency
  2. Create a script in package.json to call Webpack
  3. Run Webpack using npm run build
  4. Change the path in the script tag to point to the main.js file
  5. Create a Webpack config file to customize its behavior
  6. Install loaders for CSS, TypeScript, and Markdown
  7. Add module attribute in Webpack config
  8. Use regular expression to match file type to required loaders
💡 Snowpack builds all dependencies once and ships them directly to the browser, making it great for big complex projects with fast build times.

Related Reads

📰
The React Compiler Just Made Your Memoization Knowledge Obsolete. Here’s What to Learn Instead.
React's new compiler makes memoization knowledge obsolete, learn about automatic memoization and React's compiler optimizations instead
Medium · JavaScript
📰
You don't need a backend to store form submissions. You need a place to ask "how many."
Learn how to store form submissions without a backend and understand the importance of reporting and aggregation
Dev.to · Omer Hochman
📰
The Matrix of Layouts: CSS Grid vs Flexbox
Learn when to use CSS Grid vs Flexbox for layouts and why it matters for efficient web development
Dev.to · Timevolt
📰
Memoization useMemo()Explained: Why React Doesn’t Need to Repeat the Same Work
Learn how React's useMemo() hook uses memoization to optimize performance by avoiding redundant calculations
Medium · JavaScript
Up next
How to Use Semrush Keyword Magic Tool with ChatGPT to Make Money
Grow with Will - SEO, Sales & Entrepreneurship
Watch →