All Projects → rstacruz → Webpack Tricks

rstacruz / Webpack Tricks

Tips and tricks in using Webpack

Projects that are alternatives of or similar to Webpack Tricks

Static Html Webpack Boilerplate
🔮 modern tooling for old-school static webpage development
Stars: ✭ 226 (-90.44%)
Mutual labels:  webpack, minification
Fontmin Webpack
Minifies icon fonts to just the used glyphs.
Stars: ✭ 93 (-96.07%)
Mutual labels:  webpack, minification
Minification Benchmarks
🏃‍♂️🏃‍♀️🏃 JS minification benchmarks: babel-minify, esbuild, terser, uglify-js, swc, google closure compiler
Stars: ✭ 271 (-88.54%)
Mutual labels:  webpack, minification
Static Site Boilerplate
A better workflow for building modern static websites.
Stars: ✭ 1,633 (-30.92%)
Mutual labels:  webpack, minification
Esbuild Loader
⚡️ Speed up your Webpack build with esbuild
Stars: ✭ 1,245 (-47.34%)
Mutual labels:  webpack, minification
Code Splitting React Webpack
An example of how to code split with Webpack 2 and React Router
Stars: ✭ 138 (-94.16%)
Mutual labels:  webpack, split
Preserver
Preserver is desktop notes organiser built on electron, angular2, pouchDB
Stars: ✭ 207 (-91.24%)
Mutual labels:  webpack
React Code Splitting
Code splitting won't be a nightmare anymore !
Stars: ✭ 209 (-91.16%)
Mutual labels:  webpack
Webpack Stylish
A stylish, optionated reporter for webpack
Stars: ✭ 207 (-91.24%)
Mutual labels:  webpack
Scalajs Bundler
Stars: ✭ 206 (-91.29%)
Mutual labels:  webpack
V Selectpage
SelectPage for Vue2, list or table view of pagination, use tags for multiple selection, i18n and server side resources supports
Stars: ✭ 211 (-91.07%)
Mutual labels:  webpack
Awesome Typescript Loader
Awesome TypeScript loader for webpack
Stars: ✭ 2,357 (-0.3%)
Mutual labels:  webpack
React Expressjs
Simple and compact boilerplate for ReactJS project with expressJS
Stars: ✭ 208 (-91.2%)
Mutual labels:  webpack
Bitrix Project
Заготовка 1C Bitrix проекта: автозагрузка, композер, базовые ООП компоненты, миграции, модели, современный фронтенд стек, инструменты для деплоя.
Stars: ✭ 207 (-91.24%)
Mutual labels:  webpack
Starter Pack
Combines React (ft. hooks), Redux, Redux-saga and TypeScript with Auth0 as a starting point for modern web apps with solid authentication
Stars: ✭ 209 (-91.16%)
Mutual labels:  webpack
React Isomorphic Starterkit
Create an isomorphic React app in less than 5 minutes
Stars: ✭ 2,326 (-1.61%)
Mutual labels:  webpack
Unused Files Webpack Plugin
Glob all files that are not compiled by webpack under webpack's context
Stars: ✭ 210 (-91.12%)
Mutual labels:  webpack
React Cordova Boilerplate
TodoMVC example for react with development tools to build a cordova application
Stars: ✭ 206 (-91.29%)
Mutual labels:  webpack
Remember
The progressive offline Todo app
Stars: ✭ 208 (-91.2%)
Mutual labels:  webpack
Webpack Merge
Merge designed for webpack
Stars: ✭ 2,484 (+5.08%)
Mutual labels:  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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].