• Stars
    star
    2,359
  • Rank 18,682 (Top 0.4 %)
  • Language
  • Created over 7 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tips and tricks in using Webpack

Webpack tricks

Just a small catalog of Webpack tips and tricks I've learned. These tricks work with Webpack v3 unless otherwise specified.

Table of contents

Progress reporting

Invoke Webpack with:

--progress --colors

Minification

Invoke Webpack with -p for production builds. In Webpack 2, this also automatically sets process.env.NODE_ENV === 'production'.

webpack -p

Multiple bundles

Export multiple bundles by setting the output to [name].js. This example produces a.js and b.js.

module.exports = {
  entry: {
    a: './a',
    b: './b'
  },
  output: { filename: '[name].js' }
}

Concerned about duplication? Use the CommonsChunkPlugin to move the common parts into a new output file.

plugins: [ new webpack.optimize.CommonsChunkPlugin('init.js') ]
<script src='init.js'></script>
<script src='a.js'></script>

Split app and vendor code

Use CommonsChunkPlugin to move vendor code into vendor.js.

var webpack = require('webpack')

module.exports = {
  entry: {
    app: './app.js',
    vendor: ['jquery', 'underscore', ...]
  },

  output: {
    filename: '[name].js'
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin('vendor')
  ]
}

How this works:

  • We make a vendor entry point and load it with some libraries
  • CommonsChunkPlugin will remove these libraries from app.js (because it appears in 2 bundles now)
  • CommonsChunkPlugin also moves the Webpack runtime into vendor.js

Reference: Code splitting

Source maps (Webpack 1)

The best source maps option is cheap-module-eval-source-map. This shows original source files in Chrome/Firefox dev tools. It's faster than source-map and eval-source-map.

// Webpack 1 only
const DEBUG = process.env.NODE_ENV !== 'production'

module.exports = {
  debug: DEBUG ? true : false,
  devtool: DEBUG ? 'cheap-module-eval-source-map' : 'hidden-source-map'
}

Your files will now show up in Chrome Devtools as webpack:///foo.js?a93h. We want this to be cleaner like webpack:///path/to/foo.js.

output: {
	devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]'
}

Reference: devtool documentation

Source maps (Webpack 2-3)

The best source maps option is cheap-module-source-map. The cheap-module-eval-source-map strategy no longer shows correct traces in Chrome/Firefox.

// Webpack 2 only
const DEBUG = process.env.NODE_ENV !== 'production'

module.exports = {
  devtool: DEBUG ? 'cheap-module-source-map' : 'hidden-source-map'
}

If you're using extract-text-webpack-plugin, use 'source-map' instead. CSS sourcemaps won't work otherwise.

// Only if you're using extract-text-webpack-plugin
module.exports = {
  devtool: DEBUG ? 'source-map' : 'hidden-source-map'
}

Your files will now show up in Chrome Devtools as webpack:///foo.js?a93h. We want this to be cleaner like webpack:///path/to/foo.js.

output: {
  devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]'
}

Reference: devtool documentation

Output CSS files

This is complicated, and the guide can be found here.

Development mode

Want to have certain options only appear in development mode?

const DEBUG = process.env.NODE_ENV !== 'production'

// Webpack 1
module.exports = {
  debug: DEBUG ? true : false,
  devtool: DEBUG ? 'cheap-module-eval-source-map' : 'hidden-source-map'
}

// Webpack 2
module.exports = {
  devtool: DEBUG ? 'cheap-module-source-map' : 'hidden-source-map'
}

Webpack 1: Be sure to invoke Webpack as env NODE_ENV=production webpack -p when building your production assets.

Webpack 2: Invoke Webpack as webpack -p when building your production assets. NODE_ENV is automatically set by Webpack.

Investigating bundle sizes

Want to see what dependencies are the largest? You can use webpack-bundle-size-analyzer.

$ yarn global add webpack-bundle-size-analyzer

$ ./node_modules/.bin/webpack --json | webpack-bundle-size-analyzer
jquery: 260.93 KB (37.1%)
moment: 137.34 KB (19.5%)
parsleyjs: 87.88 KB (12.5%)
bootstrap-sass: 68.07 KB (9.68%)
...

If you're generating source maps (you should), you can also use source-map-explorer, which also works outside of Webpack.

$ yarn global add source-map-explorer

$ source-map-explorer bundle.min.js bundle.min.js.map

Reference: webpack-bundle-size-analyzer, source-map-explorer

Smaller React

React will build dev tools by default. You don't need this in production. Use the EnvironmentPlugin to make these dev tools disappear. This saves you around 30kb.

plugins: [
  new webpack.EnvironmentPlugin({
    NODE_ENV: 'development'
  })
]

Webpack 1: Be sure to invoke Webpack as env NODE_ENV=production webpack -p when building your production assets.

Webpack 2: Invoke Webpack as webpack -p when building your production assets. NODE_ENV is automatically set by Webpack.

Reference: EnvironmentPlugin documentation

Smaller Lodash

Lodash is very useful but usually we only need a small part of its full functionality. lodash-webpack-plugin can help you shrink the lodash build by replacing feature sets of modules with noop, identity, or simpler alternatives.

const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

const config = {
  plugins: [
    new LodashModuleReplacementPlugin({
      path: true,
      flattening: true
    })
  ]
};

This may save you >10kb depending on how much you use lodash.

Requiring all files in a folder

Ever wanted to do this?

require('./behaviors/*')  /* Doesn't work! */

Use require.context.

// http://stackoverflow.com/a/30652110/873870
function requireAll (r) { r.keys().forEach(r) }

requireAll(require.context('./behaviors/', true, /\.js$/))

Reference: require.context

Clean up extract-text-webpack-plugin log

If you're seeing this in your debug log when using extract-text-webpack-plugin:

Child extract-text-webpack-plugin:
        + 2 hidden modules
Child extract-text-webpack-plugin:
        + 2 hidden modules
Child extract-text-webpack-plugin:
        + 2 hidden modules

Turn it off using stats: { children: false }.

/* webpack.config.js */
stats: {
  children: false,
},

Reference: extract-text-webpack-plugin#35

More Repositories

1

nprogress

For slim progress bars like on YouTube, Medium, etc
JavaScript
25,552
star
2

cheatsheets

My cheatsheets
SCSS
13,391
star
3

jquery.transit

Super-smooth CSS3 transformations and transitions for jQuery
JavaScript
7,328
star
4

rscss

Reasonable System for CSS Stylesheet Structure
3,894
star
5

flatdoc

Build sites fast from Markdown
CSS
2,679
star
6

sparkup

A parser for a condensed HTML format
Python
1,562
star
7

backbone-patterns

Common Backbone.js usage patterns.
760
star
8

remount

Mount React components to the DOM using custom elements
JavaScript
675
star
9

sinatra-assetpack

Package your assets transparently in Sinatra.
CSS
542
star
10

jsdom-global

Enable DOM in Node.js
JavaScript
472
star
11

hicat

Command-line syntax highlighter
JavaScript
405
star
12

kingraph

Plots family trees using JavaScript and Graphviz
JavaScript
390
star
13

vim-closer

Closes brackets
Vim Script
329
star
14

scour

Traverse objects and arrays with ease
JavaScript
308
star
15

mocha-jsdom

Simple jsdom integration with mocha
JavaScript
254
star
16

css-condense

[unsupported] A CSS compressor that shows no mercy
JavaScript
206
star
17

swipeshow

The unassuming touch-enabled JavaScript slideshow
JavaScript
191
star
18

rsjs

Reasonable System for JavaScript Structure
181
star
19

vim-coc-settings

My Vim settings for setting it up like an IDE
Vim Script
164
star
20

startup-name-generator

Let's name your silly startup
JavaScript
164
star
21

onmount

Safe, reliable, idempotent and testable behaviors for DOM nodes
JavaScript
156
star
22

psdinfo

Inspect PSD files from the command line
JavaScript
147
star
23

vim-hyperstyle

Write CSS faster
Python
144
star
24

vim-from-scratch

Rico's guide for setting up Vim
144
star
25

js2coffee.py

JS to CoffeeScript compiler. [DEPRECATED]
Python
127
star
26

firefox-stealthfox

Firefox customization for stealth toolbars
CSS
122
star
27

mocha-clean

Clean up mocha stack traces
JavaScript
107
star
28

jquery-stuff

A collection of small jQuery trinkets
JavaScript
96
star
29

npm-pipeline-rails

Use npm as part of your Rails asset pipeline
Ruby
95
star
30

navstack

Manages multiple screens with mobile-friendly transitions
JavaScript
94
star
31

bootstrap-practices

List of practices when using Bootstrap in projects
90
star
32

details-polyfill

Polyfill for the HTML5 <details> element, no dependencies
JavaScript
89
star
33

dom101

DOM manipulation utilities
JavaScript
82
star
34

unorphan

Removes text orphans
JavaScript
81
star
35

expug

Pug templates for Elixir
Elixir
80
star
36

stylelint-rscss

Validate CSS with RSCSS conventions
JavaScript
74
star
37

feh-blur-wallpaper

Blur your desktop wallpaper when windows are open
Shell
73
star
38

pomo.js

Command-line timer, great for Pomodoros
JavaScript
73
star
39

sinatra-backbone

Neat Backbone.js integration with Sinatra.
Ruby
72
star
40

flowloop

A Pomodoro-like timer for hyper-productivity
JavaScript
71
star
41

vimfiles

My VIM config files.
Lua
63
star
42

bookmarks

My bookmarks
63
star
43

my_qmk_keymaps

Keymaps for keyboards
C
59
star
44

typish

Typewriter simulator
JavaScript
58
star
45

iconfonts

Fine-tuned icon fonts integration for Sass, Less and Stylus
CSS
54
star
46

pre.js

Efficient, resilient resource preloader for JS/CSS
JavaScript
54
star
47

tape-watch

Rerun tape tests when files change
JavaScript
53
star
48

tinkerbin

Tinkerbin.com
JavaScript
52
star
49

vim-fastunite

Search for files fast
Vim Script
48
star
50

collaborative-etiquette

A manifesto for happy Open Source projects
46
star
51

decca

Render interfaces using pure functions and virtual DOM
JavaScript
45
star
52

vim-opinion

My opinionated vim defaults
Vim Script
44
star
53

modern-development

Using agile methods to build quality web applications
CSS
43
star
54

til-2013

Old version of http://ricostacruz.com/til (2015-2018)
CSS
42
star
55

ion

[deprecated] Ruby/Redis search engine.
Ruby
41
star
56

timetip

Deliciously-minimal time tracker for the command-line
JavaScript
40
star
57

vim-xtract

Extract the selection into a new file
Vim Script
39
star
58

bump-cli

Command-line version incrementer
JavaScript
39
star
59

halla

Native Slack wrapper app without the bloat
JavaScript
38
star
60

newsreader-sample-layout

CSS
36
star
61

ento

Simple, stateful, observable objects in JavaScript
JavaScript
36
star
62

cron-scheduler

Runs jobs in periodic intervals
JavaScript
35
star
63

promise-conditional

Use if-then-else in promise chains
JavaScript
34
star
64

ractive-touch

Touch events for Ractive
JavaScript
33
star
65

git-update-ghpages

Simple tool to update GitHub pages
Shell
33
star
66

jquery.unorphan

[deprecated] Obliterate text orphans.
JavaScript
33
star
67

greader

[UNSUPPORTED] Google Reader API client for Ruby
Ruby
32
star
68

penpad

Design and document web UI components
TypeScript
32
star
69

typecat

TypeScript
31
star
70

react-meta-elements

Sets document title and meta tags using React elements or hooks
TypeScript
31
star
71

vim-ultisnips-css

[deprecated] Write CSS in VIM faster.
Ruby
31
star
72

tape-plus

Nested tape tests with before/after, async, and promise support
JavaScript
30
star
73

taskpaper.js

Taskpaper parser in JavaScript
JavaScript
28
star
74

frontend-starter-kit

Rico's opinionated Metalsmith frontend kit
JavaScript
28
star
75

homebrew-backup

Back up your Homebrew profile
Shell
28
star
76

fishfiles

my fish-shell config files
Shell
28
star
77

passwordgen.js

Password generator for the command line
JavaScript
28
star
78

reacco

Generate documentation from README files.
Ruby
26
star
79

ghub

Open this project in github
Shell
26
star
80

sass_icon_fonts

Sass 3.2 integration with modern icon fonts.
CSS
26
star
81

lidoc

[Deprecated] Literate-programming style documentation tool.
CoffeeScript
24
star
82

rspec-repeat

Repeats an RSpec example until it succeeds.
Ruby
24
star
83

lofi

VHS music machine from the 80's
JavaScript
24
star
84

sinatra-template

Ruby
24
star
85

fish-asdf

Fish shell integrations for asdf version manager
Shell
24
star
86

wiki

Stuff
23
star
87

arch-installer

Install UI for Arch Linux
Shell
22
star
88

slack-emoji-magic

Magic: the Gathering emojis
Makefile
21
star
89

node-hledger

Node.js API for hledger
JavaScript
21
star
90

vimbower

Use bower, git and pathogen to manage your vim setup
21
star
91

ractive-promise-alt

Adaptor for Ractive.js to support promises
JavaScript
21
star
92

til-2020

Today I learned blog of @rstacruz
TypeScript
21
star
93

webpack-starter-kit

Baseline configuration for Webpack
JavaScript
21
star
94

phoenix_expug

Expug integration for Phoenix
JavaScript
20
star
95

cssutils

Collection of Sass utility mixins and other goodies.
CSS
20
star
96

responsive-modular-scale.css

Responsive typography using CSS variables
20
star
97

cdnjs-command

Command line helper for cdnjs.com
Ruby
20
star
98

curlformat

CLI utility to clean up your "Copy as cURL" strings
JavaScript
19
star
99

ractive-loader

ractive template loader for webpack
JavaScript
19
star
100

ajaxapi

Minimal AJAX library for APIs. Supports promises
JavaScript
18
star