What is Webpack?
Once upon a time, there was only
HTML was the only building block of the whole web.
<script> alert("Welcome to my website") </script>
When dealing with a lot of code, we want to split our code into small pieces. It makes our code more readable and maintainable. You are probably already familiar with the import-export syntax. This is code-splitting.
But eventually, we will want to transform all of our files into (usually) one big bundle. This bundle should be optimized and should work (polyfill) on all the browsers we expect our code will run at.
Webpack does exactly that. It will run on build time and create an optimized bundle of your code (-small-sized bundle). For example, it can change the name of your variables from:
const example = 10;
var e = 10;
Another aspect, as mentioned, is Polyfilling. We can configure our Webpack setup to make our code run on the browsers we define for it. This is actually done with the help of another library (usually Babel).
In the example above, Webpack is changing the const keyword to var, to make it work on more browsers.
Let's go through a basic Webpack configuration for a React app (open the attached picture side by side).
Entry - the entry destination is the main file we want Webpack to start its bundling. We only have to specify one file and Webpack will figure out the rest by looking for its dependencies. Here we specify the index.js file which is the place where we render our App in React (and all other files are just siblings of it).
Output - is the path where we want our bundle to be. We specify directory name (here it's dist) and we can also specify the file name we want to output.
Loaders - Webpack is not very smart. It understands only JS and JSON files. If we want Wepback to understand JSX, for example, we have to specify loaders that will translate it for Webpack. Here we specify the babel-loader and set its options to work with JSX (React).
Plugins - These help us to make our code more optimized and handle assets. In our example, we use the HtmlWebpackPlugin. This plugin will generate an HTML file and will automatically inject our JS bundle into it.
Don't be afraid of your Webpack. It's a great tool and you should be comfortable enough with it so you can make config changes to it.
I encourage you to go and play with Webpack.