Taking Notes of Webpack
Webpack is the most popular module bundler in JavaScript world.
There are more and more single page applications on the Internet. Lots of code is on the client side. Therefore, we need a better module bundler to help us organise our modules or split our code into modules.
In past, we import our JavaScript files one by one:
<script src="module1.js"></script>
<script src="module2.js"></script>
<script src="libraryA.js"></script>
<script src="module3.js"></script>
Some common problems of that style are:
- Not easy to organise. When there are 10 modules, we have to import one module per script tag. How about 20 modules? even 100 modules?
- Global namespace pollution. Every script imported will export an interface to a global object. It causes conflicts.
- Order of loading is important. Some modules depend on other modules or libraries; i.e. we have to load jQuery or some commonly used libraries first.
Transferring
Modules are transferred to browser by server. There are two extremes on how to transfer modules:
- One request per module: It will slow down page’s loading and thus is not good for web performance.
- All modules in one request: When the concatenated single file grows larger, it may be 5MB, 10MB, 20MB… It will take forever to load!
Is there a tool making it easy to split or concatenate modules into the best number of files we want?
Not Only JavaScript
We treat a JavaScript file as a module. That is good.
Stylesheet can be treated as module via some precompiler or post production, i.e. SASS and LESS.
Now, we can load more static resources as modules: stylesheets, images, fonts, html for templating, and more!
Require Your Modules Everywhere in JavaScript!
Webpack supports AMD and CommonJS styles, so you can access your resource in your JavaScript code.
CommonJS style:
//JSX syntax for React App
<img src={require('images/myAwesomePhoto')} />
Goals of Webpack
(from official documentation)
- Split the dependency tree into chunks loaded on demand
- Keep initial loading time low
- Every static asset should be able to be a module
- Ability to integrate 3rd-party libraries as modules
- Ability to customize nearly every part of the module bundler
- Suited for big projects
Webpack is awesome. Let’s dive into Webpack!