# Bundlers
---
## Historical context
---
### One big JS file
- Everything shares the same scope/globals
- Git conflicts :crying_cat_face:
---
### Multiple files
- Have to include in the right order
- Everything is still global
- Only solves the big messy file problem
---
### Module pattern
- No more globals
- Weird and complicated
- Immediately-invoked function expressions (IIFEs)
---
#### Remember this workshop?
```javascript
const Calculator = (function createCalculator () {
let state = 0;
return {
add: x => state += x,
read: () => state,
}
})();
Calculator.add(3);
Calculator.read(); // returns 3;
```
---
### ES Modules
- Web standard version of Node require
- Modular chunks of code
- Obvious what relies on what
- No globals
---
### ES Modules
```javascript
// add.js
const add = (x, y) => x + y;
export default add; // "default" export (only one per file)
```
```javascript
// numbers.js
const y = 2;
const z = 3;
export { y, z }; // "named" export
```
```javascript
// main.js
import whateverNameYouWant from "./add.js";
import { x, y } from "./numbers.js"; // names must match
```
---
## What are bundlers for?
- Make ES Modules work
- Smush them into one (or more) JS files
- Transform the code along the way
- minification
- transpilation (Babel)
- including non-JS assets (`import './style.css'`)
---
## Optimisations
---
Turn nice-to-write code into nice-to-run code.
```javascript
import add from "./add";
add(1, 2);
```
turns into
```javascript
(function(){function a(x,y){return x+y};a(1,2)}())
```
---
"Tree shake" out unused code
```javascript
import { add, divide } from "./maths";
add(1, 2); // divide will be removed from final bundle
```
---
Split your code into different bundles
```javascript
// home page
import { add } from "./maths";
add(1, 2);
```
```javascript
// about page
import { divide } from "./maths";
divide(3, 2);
```
---
## Examples of bundlers
- WebPack (most popular)
- Parcel (zero-config)
- Browserify (the original)
- Rollup (mostly for libraries)
{"metaMigratedAt":"2023-06-14T15:29:45.107Z","metaMigratedFrom":"Content","title":"Bundlers","breaks":true,"contributors":"[{\"id\":\"95766997-b355-49e6-8c38-077c6a7ebb3b\",\"add\":1487,\"del\":371},{\"id\":\"597800ad-7cf0-4ccd-adc0-d5ff22d0bf60\",\"add\":2,\"del\":0}]"}