Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

The modern JS developer's workflow

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

The modern developer's webpack workflow

Slide 5

Slide 5 text

1. Google: "how to do X in webpack"

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

3. Copy and paste

Slide 8

Slide 8 text

4. It works, for now

Slide 9

Slide 9 text

5. But then you need to tweak it

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

Boilerplates are great, once you know the tool

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

It doesn't have to be like this

Slide 15

Slide 15 text

Firstly: do you actually need webpack?

Slide 16

Slide 16 text

Glen Madern: https://frontend.center/

Slide 17

Slide 17 text

What is webpack?

Slide 18

Slide 18 text

"An ahead of time compiler for the browser"

Slide 19

Slide 19 text

webpack does what the browser would do if given your app: » find all images in your CSS and download them » parse your JavaScript dependencies and download them » parse all CSS for imports and download them

Slide 20

Slide 20 text

webpack can do this right at the beginning And create a more optimised bundle, saving the browser (and user) time

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

webpack is not just for JavaScript

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

webpack Terminology to tell your friends

Slide 27

Slide 27 text

A module Any file that your application uses. Not just JavaScript. CSS, images, text files, anything.

Slide 28

Slide 28 text

Chunk A file, or a group of files that webpack has squashed together

Slide 29

Slide 29 text

Entry point A file webpack will search from to find dependencies and modules

Slide 30

Slide 30 text

A loader A function that takes a file's source and transforms it to return a new source file

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

Let's do it

Slide 33

Slide 33 text

npm init -y PSA: Don't install things globally!

Slide 34

Slide 34 text

npm install --save-dev [email protected] Run locally with ./node_modules/.bin/webpack (Or add ./node_modules/.bin to your $PATH)

Slide 35

Slide 35 text

index.html Github

Slide 36

Slide 36 text

src/main.js fetch('https://api.github.com/users/jackfranklin') .then(function(d) { return d.json() }) .then(function(data) { console.log('Got github data', data) })

Slide 37

Slide 37 text

Configuring webpack » Where should webpack start looking? » Where should it output to?

Slide 38

Slide 38 text

webpack.config.js var path = require('path') module.exports = { // where should it look? entry: path.resolve('src', 'main.js'), // where should it output to? output: { path: path.resolve(__dirname, 'dist'), filename: 'main.js', publicPath: '/dist/' } }

Slide 39

Slide 39 text

run webpack Hash: c09c87fc891968a374a6 Version: webpack 2.1.0-beta.26 Time: 70ms Asset Size Chunks Chunk Names main.js 2.63 kB 0 [emitted] main [0] ./src/main.js 194 bytes {0} [built]

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

Watching for changes webpack --watch "scripts": { "build:dev": "webpack --watch" }

Slide 42

Slide 42 text

webpack is watching the files… Hash: c09c87fc891968a374a6 Version: webpack 2.1.0-beta.26 Time: 103ms Asset Size Chunks Chunk Names main.js 2.63 kB 0 [emitted] main [0] ./src/main.js 194 bytes {0} [built] Hash: d9aad0a1ca8f706975ad Version: webpack 2.1.0-beta.26 Time: 11ms Asset Size Chunks Chunk Names main.js 2.6 kB 0 [emitted] main [0] ./src/main.js 163 bytes {0} [built]

Slide 43

Slide 43 text

Refreshing is so much effort npm install --save-dev [email protected] beta.11

Slide 44

Slide 44 text

webpack-dev-server Project is running at http://localhost:8080/ webpack output is served from /dist/ Hash: 1d366a627611ba06845c Version: webpack 2.1.0-beta.26 Time: 947ms Asset Size Chunks Chunk Names main.js 247 kB 0 [emitted] main chunk {0} main.js (main) 233 kB [entry] [rendered] [0] ./~/inherits/inherits_browser.js 672 bytes {0} [built] [1] (webpack)/buildin/global.js 506 bytes {0} [built] [2] ./~/debug/browser.js 3.76 kB {0} [built] [3] ./~/process/browser.js 5.3 kB {0} [built] ...

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

"scripts": { "build:dev": "webpack --watch", "start": "webpack-dev-server" },

Slide 47

Slide 47 text

Loaders fetch('https://api.github.com/users/jackfranklin') .then(function(d) { return d.json() }) .then(function(data) { console.log('Got github data', data) }) Would be much nicer as: const username = 'jackfranklin' fetch(`https://api.github.com/users/${username}`) .then(d => d.json()) .then(data => console.log('Got github data', data))

Slide 48

Slide 48 text

Babel npm install --save-dev babel-core npm install --save-dev babel-preset-es2015 npm install --save-dev babel-loader

Slide 49

Slide 49 text

webpack.config.js module.exports = { entry: path.resolve('src', 'main.js'), output: { ... }, module: { rules: [ ] } }

Slide 50

Slide 50 text

webpack rules Apply transformations to certain files.

Slide 51

Slide 51 text

{ // apply this rule to any files that end in ".js" test: /\.js$/, // only look for files in the src directory include: path.resolve('src'), // configure the loaders for this rule use: [{ }] }

Slide 52

Slide 52 text

{ test: /\.js$/, include: path.resolve('src'), use: [{ // for files that this rule applies to // run the babel-loader against them loader: 'babel-loader', // specific options for the babel loader options: { presets: ['es2015'] } }] }

Slide 53

Slide 53 text

src/main.js const username = 'jackfranklin' fetch(`https://api.github.com/users/${username}`) .then(d => d.json()) .then(d => console.log('Got Github data', d))

Slide 54

Slide 54 text

Restart dev server

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

npm install --save whatwg-fetch

Slide 58

Slide 58 text

Entry points entry: { main: [ 'whatwg-fetch', path.resolve('src', 'main.js') ] },

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

Let's make it a bit more interactive

Slide 62

Slide 62 text

Go!

Slide 63

Slide 63 text

const form = document.getElementById('github-form') form.addEventListener('submit', e => { e.preventDefault() const username = document.getElementById('input-box').value fetchPerson(username) })

Slide 64

Slide 64 text

const fetchPerson = username => fetch(`https://api.github.com/users/${username}`) .then(d => d.json()) .then(displayPerson)

Slide 65

Slide 65 text

const displayPerson = user => document.getElementById('results').innerHTML = `

${user.name}

${user.company}

${user.bio || 'No Bio :('}

`

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

Let's get some CSS in here Remember, the goal of webpack is for it to manage all our assets, CSS included. This is weird at first but stick with me... (Also I suck at design, please forgive)

Slide 68

Slide 68 text

form { width: 200px; margin: 10px auto; } #results { width: 300px; margin: 0 auto; border: 1px solid #111; background: #ddd; }

Slide 69

Slide 69 text

import './style.css' const username = 'jackfranklin' ...

Slide 70

Slide 70 text

ERROR in ./src/style.css Module parse failed: /github-app/src/style.css Unexpected token (1:5) You may need an appropriate loader to handle this file type. | form { | width: 200px; | margin: 10px auto; @ ./src/main.js 3:0-22 @ multi main

Slide 71

Slide 71 text

npm install --save-dev css-loader npm install --save-dev style-loader » CSS Loader: parses CSS files » Style Loader: dynamically inserts stylesheets into HTML

Slide 72

Slide 72 text

Add another rule { test: /\.css$/, include: path.resolve('src'), use: [{ loader: 'style-loader', }, { loader: 'css-loader', }] } Loaders are applied from right to left, or bottom to top

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

No content

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

No content

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

Restart webpack-dev-server

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

Deploying to Production

Slide 85

Slide 85 text

Configuring webpack differently

Slide 86

Slide 86 text

"scripts": { "build:dev": "webpack --watch", "build:prod": "NODE_ENV=production webpack", "start": "webpack-dev-server" },

Slide 87

Slide 87 text

npm install --save-dev webpack- config-utils

Slide 88

Slide 88 text

var { getIfUtils, removeEmpty } = require('webpack-config-utils') var { ifProduction, ifNotProduction } = getIfUtils(process.env.NODE_ENV || 'development') » removeEmpty: removes undefined from arrays » ifProduction: returns what it's given if NODE_ENV === 'production' » ifNotProduction: returns what it's given if NODE_ENV !== 'production'

Slide 89

Slide 89 text

Starting point npm run build:prod - main.js: 24.9kb (All CSS is contained within main.js and dynamically inserted)

Slide 90

Slide 90 text

Plugins A webpack plugin will typically work on the bundle as a whole, rather than on individual files.

Slide 91

Slide 91 text

Minifying var webpack = require('webpack') ... output: { ... }, plugins: removeEmpty([ ifProduction(new webpack.optimize.UglifyJsPlugin()) ]), module: { ... }

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

npm run build:prod - main.js: 11.4kb

Slide 96

Slide 96 text

Nice, but why have the CSS injected with JavaScript? npm install --save-dev [email protected]

Slide 97

Slide 97 text

var ExtractTextPlugin = require('extract-text-webpack-plugin') ... plugins: removeEmpty([ ifProduction(new webpack.optimize.UglifyJsPlugin()), new ExtractTextPlugin('style.css'), ]),

Slide 98

Slide 98 text

{ test: /\.css$/, include: path.resolve('src'), loader: ExtractTextPlugin.extract('css-loader'), }

Slide 99

Slide 99 text

No content

Slide 100

Slide 100 text

Deep breaths, lots of progress! npm run build:prod - main.js: 7.46kb - style.css: 140bytes

Slide 101

Slide 101 text

Finally: code splitting / lazy loading

Slide 102

Slide 102 text

We should keep our first page load super quick » download JS » parse JS » execute JS This takes time.

Slide 103

Slide 103 text

src/fetch-person.js export const fetchPerson = username => fetch(`https://api.github.com/users/${username}`) .then(d => d.json()) .then(displayPerson) const displayPerson = user => document.getElementById('results').innerHTML = `

${user.name}

${user.company}

${user.bio || 'No Bio :('}

`

Slide 104

Slide 104 text

import './style.css' import { fetchPerson } from './fetch-person' const form = document.getElementById('github-form') form.addEventListener('submit', e => { e.preventDefault() const username = document.getElementById('input-box').value fetchPerson(username) })

Slide 105

Slide 105 text

We only need fetchPerson if the user clicks the button

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

import './style.css' const form = document.getElementById('github-form') form.addEventListener('submit', e => { e.preventDefault() const username = document.getElementById('input-box').value System.import('./fetch-person') .then(module => module.fetchPerson) .then(fetchPerson => fetchPerson(username)) })

Slide 108

Slide 108 text

No content

Slide 109

Slide 109 text

And now we can build to production:

Slide 110

Slide 110 text

npm run build:prod - main.js: 8.08kb - 0.main.js: 387bytes - style.css: 140bytes

Slide 111

Slide 111 text

Wait, the build went up? This is a contrived example, because this app is tiny! You pay a small cost because webpack has code that it inserts for lazily loading modules, but if your pages are big enough you'll get still save.

Slide 112

Slide 112 text

No content

Slide 113

Slide 113 text

No Lazy loading bundle.app.193adde67586dd61304b.js 444 kB

Slide 114

Slide 114 text

Lazily loading the graph component bundle.0.513a048a93c5b8f1687b.js 431 kB bundle.app.ce8bc2ebcec6edbff6a1.js 13.1 kB

Slide 115

Slide 115 text

400kb first load saving

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

No content

Slide 118

Slide 118 text

No content

Slide 119

Slide 119 text

Lazy loading: not a silver bullet But when you do want it, webpack makes it easy :)

Slide 120

Slide 120 text

Bonus: dead code elimination webpack 2 can parse ES2015 modules, that is: import { x } from './y' export default function foo() {...}

Slide 121

Slide 121 text

ES2015 module imports and exports have to be static. So we can go through them and see which ones are used and which ones aren't needed. This means we can eliminate any code relating to ununsed exports!

Slide 122

Slide 122 text

src/not-used.js export const SO_NOT_USED = 'I AM NOT USED BY ANYTHING EVER' export const SO_USED = 'I GET USED BY THINGS' src/main.js import { SO_USED } from './not-used' console.log(SO_USED)

Slide 123

Slide 123 text

Stop Babel converting modules Stop Babel converting: use: [{ loader: 'babel-loader', options: { presets: [['es2015', { modules: false }]] } }]

Slide 124

Slide 124 text

webpack 2 + ES2015 modules = smaller builds, for free!

Slide 125

Slide 125 text

I've barely scratched the surface.

Slide 126

Slide 126 text

webpack 2 » Much improved documentation & community engagement » Improved configuration with a nicer API and automatic validation of config » Tree shaking, easier code splitting and lazy loading » More performant

Slide 127

Slide 127 text

Fin » Slides & code: https://github.com/jackfranklin/half-stack- webpack » webpack 2: webpack.js.org » Me: @Jack_Franklin, javascriptplayground.com, elmplayground.com Thanks to: Glen Maddern, Sean Larkinn, Kent C Dodds