Webpack and Babel weirded me out for a long time. Luckily Create-react-app always took care of all of that stuff for me so I never had to peek into what it does. Turns out it's not all that complicated and learning it is a crucial step if you want to become a better developer.
Webpack is a module bundler.
Great, but what does that mean?
To understand that we have to go through a bit of history:
<script> alert('stay on this page to win 1000000$ !!!1!') </script>
So instead of
node_modules/some_package/index.js you only get 1
bundle.js file that includes the code from all of them.
Webpack now also has a ton of custom loaders to include not just js files but also fonts, CSS files, images and pretty much anything else you could imagine. (A custom loader is just a file that tells webpack how to include something like an image in your bundle). It also automatically removes all variables that you don't use from your bundle (this is called threeshaking) and does a ton of other cool stuff to make your bundle smaller (since every user of your website has to download your bundle before being able to use it a smaller bundle means faster page load).
You can read more about the history of webpack here
Is that different from a module bundler?
Yes! Babel was born out of a need for backwards compatibility. Your websites probably need to support old browsers, sometimes as old as IE9.
.then(). Babel takes your code and rewrites it as backwards-compatible code (compiles it). So
const myName = 'tim' becomes
var myName = 'tim'. Babel makes sure that everything still works as intended, so for example when you try to reassign
myName it creates an error (since
const can't be reassigned).
Play around with it here
It can also transform syntax like react's jsx
The modern web development setup now takes care in 2 places:
- Compilation and Bundling (which happens in NodeJs on your computer)
- Execution (Which usually happens in the user's browser)
If you're interested in getting to know any of these topics deeper I recommend doing any of the following:
- Set up a complete react setup (with babel and jsx) using only the webpack and babel docs
- Learn about all the different module systems used today (cjs, es6 import, amd)
- Learn about AST's and write your own babel plugin (I swear its easier than it sounds)
Hope this post helped clear some things up. If you have any feedback on this blogpost leave a comment down below, I really appreciate it!