config

NormalModuleReplacementPlugin

  1. new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource)

Replace resources that matches resourceRegExp with newResource. If newResource is relative, it is resolve relative to the previous resource.
If newResource is a function, it is expected to overwrite the ‘request’ attribute of the supplied object.

ContextReplacementPlugin

  1. new webpack.ContextReplacementPlugin(
  2. resourceRegExp,
  3. [newContentResource],
  4. [newContentRecursive],
  5. [newContentRegExp])

If the resource (directory) matches resourceRegExp, the plugin replaces the default resource, recursive flag or regExp generated by parsing with newContentResource, newContentRecursive or newContextRegExp respectively. If newContentResource is relative, it is resolve relative to the previous resource.
If newContentResource is a function, it is expected to overwrite the ‘request’ attribute of the supplied object.

IgnorePlugin

  1. new webpack.IgnorePlugin(requestRegExp, [contextRegExp])

Don’t generate modules for requests matching the provided RegExp.

  • requestRegExp A RegExp to test the request against.
  • contextRegExp (optional) A RegExp to test the context (directory) against.

PrefetchPlugin

  1. new webpack.PrefetchPlugin([context], request)

A request for a normal module, which is resolved and built even before a require to it occurs. This can boost performance. Try to profile the build first to determine clever prefetching points.

context a absolute path to a directory

request a request string for a normal module

ResolverPlugin

  1. new webpack.ResolverPlugin(plugins, [types])

Apply a plugin (or array of plugins) to one or more resolvers (as specified in types).

plugins a plugin or an array of plugins that should be applied to the resolver(s).

types a resolver type or an array of resolver types (default: ["normal"], resolver types: normal, context, loader)

All plugins from enhanced-resolve are exported as properties for the ResolverPlugin.

Example:

  1. new webpack.ResolverPlugin([
  2. new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
  3. ], ["normal", "loader"])

ResolverPlugin.FileAppendPlugin

This plugin will append a path to the module directory to find a match, which can be useful if you have a module which has an incorrect “main” entry in its package.json/bower.json etc (e.g. "main": "Gruntfile.js"). You can use this plugin as a special case to load the correct file for this module. Example:

  1. new webpack.ResolverPlugin([
  2. new webpack.ResolverPlugin.FileAppendPlugin(['/dist/compiled-moduled.js'])
  3. ])

EnvironmentPlugin

This plugin will allow you to access to referenced environment variables through process.env

  1. new webpack.EnvironmentPlugin([
  2. "NODE_ENV"
  3. ])

In your code:

  1. var env = process.env.NODE_ENV;

output

BannerPlugin

  1. new webpack.BannerPlugin(banner, options)

Adds a banner to the top of each generated chunk.

banner a string, it will be wrapped in a comment

options.raw if true, banner will not be wrapped in a comment

options.entryOnly if true, the banner will only be added to the entry chunks.

optimize

DedupePlugin

  1. new webpack.optimize.DedupePlugin()

Search for equal or similar files and deduplicate them in the output. This comes with some overhead for the entry chunk, but can reduce file size effectively.

This doesn’t change the module semantics at all. Don’t expect to solve problems with multiple module instance. They won’t be one instance after deduplication.

Note: Don’t use it in watch mode. Only for production builds.

LimitChunkCountPlugin

  1. new webpack.optimize.LimitChunkCountPlugin(options)

Limit the chunk count to a defined value. Chunks are merged until it fits.

options.maxChunks (number) max number of chunks

options.chunkOverhead (number) an additional overhead for each chunk in bytes (default 10000, to reflect request delay)

options.entryChunkMultiplicator (number) a multiplicator for entry chunks (default 10, entry chunks are merged 10 times less likely)

MinChunkSizePlugin

  1. new webpack.optimize.MinChunkSizePlugin(options)

Merge small chunks that are lower than this min size (in chars). Size is approximated.

options.minChunkSize (number) chunks smaller than this number will be merged

OccurrenceOrderPlugin

  1. new webpack.optimize.OccurrenceOrderPlugin(preferEntry)

Assign the module and chunk ids by occurrence count. Ids that are used often get lower (shorter) ids. This make ids predictable, reduces to total file size and is recommended.

preferEntry (boolean) give entry chunks higher priority. This make entry chunks smaller but increases the overall size. (recommended)

UglifyJsPlugin

  1. new webpack.optimize.UglifyJsPlugin([options])

Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode. You can pass an object containing UglifyJS options.

  1. new webpack.optimize.UglifyJsPlugin({
  2. compress: {
  3. warnings: false
  4. }
  5. })

Additional options:

sourceMap The plugin uses SourceMaps to map error message locations to modules. This slows down the compilation. (default true)

test, include, exclude RegExp or array of RegExps to filter processed files (default test: /\.js($|\?)/i)

Mangling names configuration

A specific configuration is about mangling variable names. By default the mangle option is on. But you can configure the plugin to avoid mangling specific variable names by passing an except list:

  1. new webpack.optimize.UglifyJsPlugin({
  2. mangle: {
  3. except: ['$super', '$', 'exports', 'require']
  4. }
  5. })

With this the plugin will not mangle any occurrence of ‘$super’, ‘$’, ‘exports’ or ‘require’.

ngAnnotatePlugin npm

  1. new ngAnnotatePlugin([options]);

Runs the ng-annotate pre-minimizer to insert AngularJS dependency injection annotations.

CommonsChunkPlugin

  1. new webpack.optimize.CommonsChunkPlugin(options)
  • options.name or options.names (string|string[]): The chunk name of the commons chunk. An existing chunk can be selected by passing a name of an existing chunk. If an array of strings is passed this is equal to invoking the plugin multiple times for each chunk name. If omitted and options.async or options.children is set all chunks are used, otherwise options.filename is used as chunk name.
  • options.filename (string): The filename template for the commons chunk. Can contain the same placeholder as output.filename. If omitted the original filename is not modified (usually output.filename or output.chunkFilename.
  • options.minChunks (number|Infinity|function(module, count) -> boolean): The minimum number of chunks which need to contain a module before it’s moved into the commons chunk. The number must be greater than or equal 2 and lower than or equal to the number of chunks. Passing Infinity just creates the commons chunk, but moves no modules into it. By providing a function you can add custom logic. (Defaults to the number of chunks)
  • options.chunks (string[]`): Select the source chunks by chunk names. The chunk must be a child of the commons chunk. If omitted all entry chunks are selected.
  • options.children (boolean): If true all children of the commons chunk are selected
  • options.async (boolean): If true a new async commons chunk is created as child of options.name and sibling of options.chunks. It is loaded in parallel with options.chunks.
  • options.minSize (number): Minimum size of all common module before a commons chunk is created.

Examples:

1. Commons chunk for entries

Generate an extra chunk, which contains common modules shared between entry points.

  1. new CommonsChunkPlugin({
  2. name: "commons",
  3. // (the commons chunk name)
  4. filename: "commons.js",
  5. // (the filename of the commons chunk)
  6. // minChunks: 3,
  7. // (Modules must be shared between 3 entries)
  8. // chunks: ["pageA", "pageB"],
  9. // (Only use these entries)
  10. })

You must load the generated chunk before the entry point:

  1. <script src="commons.js" charset="utf-8"></script>
  2. <script src="entry.bundle.js" charset="utf-8"></script>

2. Explicit vendor chunk

Split your code into vendor and application.

  1. entry: {
  2. vendor: ["jquery", "other-lib"],
  3. app: "./entry"
  4. }
  5. new CommonsChunkPlugin({
  6. name: "vendor",
  7. // filename: "vendor.js"
  8. // (Give the chunk a different name)
  9. minChunks: Infinity,
  10. // (with more entries, this ensures that no other module
  11. // goes into the vendor chunk)
  12. })
  1. <script src="vendor.js" charset="utf-8"></script>
  2. <script src="app.js" charset="utf-8"></script>

Hint: In combination with long term caching you may need to use this plugin to avoid that the vendor chunk changes. You should also use records to ensure stable module ids.

3. Move common modules into the parent chunk

With Code Splitting multiple child chunks of a chunk can have common modules. You can move these common modules into the parent (This reduces overall size, but has a negative effect on the initial load time. It can be useful if it is expected that a user need to download many sibling chunks).

  1. new CommonsChunkPlugin({
  2. // names: ["app", "subPageA"]
  3. // (choose the chunks, or omit for all chunks)
  4. children: true,
  5. // (select all children of chosen chunks)
  6. // minChunks: 3,
  7. // (3 children must share the module before it's moved)
  8. })

4. Extra async commons chunk

Similar to 3., but instead of moving common modules into the parent (which increases initial load time) a new async-loaded additional commons chunk is used. This is automatically downloaded in parallel when the additional chunk is downloaded.

  1. new CommonsChunkPlugin({
  2. // names: ["app", "subPageA"]
  3. // (choose the chunks, or omit for all chunks)
  4. children: true,
  5. // (use all children of the chunk)
  6. async: true,
  7. // (create an async commons chunk)
  8. // minChunks: 3,
  9. // (3 children must share the module before it's separated)
  10. })

AggressiveMergingPlugin

  1. new webpack.optimize.AggressiveMergingPlugin(options)

A plugin for a more aggressive chunk merging strategy. Even similar chunks are merged if the total size is reduced enough. As an option modules that are not common in these chunks can be moved up the chunk tree to the parents.

options.minSizeReduce A factor which defines the minimal required size reduction for chunk merging. Defaults to 1.5 which means that the total size need to be reduce by 50% for chunk merging.

options.moveToParents When set, modules that are not in both merged chunks are moved to all parents of the chunk. Defaults to false.

options.entryChunkMultiplicator When options.moveToParents is set, moving to an entry chunk is more expensive. Defaults to 10, which means moving to an entry chunk is ten times more expensive than moving to an normal chunk.

DllPlugin

Output “dll” bundles. Dll bundles doesn’t execute any of your module’s code. They only include modules. A dll bundle exports a function which can be used to “require” modules by id (the internal require function). In addition to that a manifest json file is written to a specified location which contains mappings from real request to module id.

Combine this plugins with output.library option to expose the dll function i. e. into the global scope.

  1. new DllPlugin({
  2. path: path.join(__dirname, "manifest.json"),
  3. name: "[name]_[hash]",
  4. context: __dirname
  5. })
  • path: absolute path to the manifest json file (output)
  • name: name of the exposed dll function (keep consistent with output.library)
  • context (optional): context of requests in the manifest file, defaults to the webpack context

Usage example

DllReferencePlugin

References a dll function which is expected to be available. A manifest file can be used to map names to module ids accessible by this dll function.

Can be used to consume a dll bundle + manifest created by the DllPlugin.

Can be used in two different modes:

Scoped mode

The content of the dll is accessible under a module prefix. i. e. with scope = "xyz" a file abc in the dll can be access via require("xyz/abc").

Mapped mode

The content of the dll is mapped to the current directory. If a required file matches a file in the dll (after resolving), then the file from the dll is used instead. Note: because this happens after resolving every file in the dll must be also available for the dll user at the same path. i. e. if the dll contains jquery and the file abc, require("jquery") and require("./abc") will be used from the dll.

  1. new DllReferencePlugin({
  2. context: __dirname,
  3. scope: "xyz",
  4. manifest: require("./manifest.json"),
  5. name: "./my-dll.js",
  6. sourceType: "commonsjs2",
  7. content: { ... }
  8. })
  • context: (absolute path) context of requests in the manifest (or content property)
  • scope (optional): prefix which is used for accessing the content of the dll
  • minifest (object): an object containing content and name
  • name (optional): the name where the dll is exposed (defaults to manifest.name) (see also externals)
  • sourceType (optional): the type how the dll is exposed (defaults to "var") (see also externals)
  • content (optional): the mappings from request to module id (defaults to manifest.content)

Usage example

Using dlls via <script> tags

Dll bundle: output.library = "[name]_[hash]" output.libraryTarget = "var" DllPlugin.name = "[name]_[hash]"

Dll consumer: DllReferencePlugin.sourceType = "var"

Using dlls via node.js

Dll bundle: output.libraryTarget = "commonjs2"

Dll consumer: DllReferencePlugin.sourceType = "commonjs2" DllReferencePlugin.name = "./path/to/dll.js"

AppCachePlugin npm

Generates a HTML5 Application Cache manifest

OfflinePlugin npm

Plugin which brings offline support into your project. It generates ServiceWorker based on output files and chosen update strategy. AppCache is used as a fallback when ServiceWorker is not available.

module styles

LabeledModulesPlugin

  1. new webpack.dependencies.LabeledModulesPlugin()

Support Labeled Modules.

ComponentPlugin npm

Use component with webpack. This project has been deprecated.

AngularPlugin npm

Use angular.js modules with webpack.

dependency injection

DefinePlugin

  1. new webpack.DefinePlugin(definitions)

Define free variables. Useful for having development builds with debug logging or adding global constants.

Example:

  1. new webpack.DefinePlugin({
  2. VERSION: JSON.stringify("5fa3b9"),
  3. BROWSER_SUPPORTS_HTML5: true,
  4. TWO: "1+1",
  5. "typeof window": JSON.stringify("object")
  6. })
  1. console.log("Running App version " + VERSION);
  2. if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");

Each key passed into DefinePlugin is an identifier or multiple identifiers joined with ..

  • If the value is a string it will be used as a code fragment.
  • If the value isn’t a string, it will be stringified (including functions).
  • If the value is an object all keys are defined the same way.
  • If you prefix typeof to the key, it’s only defined for typeof calls.

The values will be inlined into the code which allows a minification pass to remove the redundant conditional.

Example:

  1. if(DEBUG)
  2. console.log('Debug info')
  3. if(PRODUCTION)
  4. console.log('Production log')
  5. ``

After passing through webpack with no minification results in:

  1. if(false)
  2. console.log('Debug info')
  3. if(true)
  4. console.log('Production log')
  5. ``

and then after a minification pass results in:

  1. console.log('Production log')
  2. ``

ProvidePlugin

  1. new webpack.ProvidePlugin(definitions)

Automatically loaded modules. Module (value) is loaded when the identifier (key) is used as free variable in a module. The identifier is filled with the exports of the loaded module.

Example:

  1. new webpack.ProvidePlugin({
  2. $: "jquery"
  3. })
  1. // in a module
  2. $("#item") // <= just works
  3. // $ is automatically set to the exports of module "jquery"

RewirePlugin npm

Use rewire in webpack.

NgRequirePlugin npm

Automatically require AngularJS modules without explicitly write require statement.

  1. {
  2. plugins: [
  3. new ngRequirePlugin(['file path list for your angular modules. eg: src/**/*.js'])
  4. ]
  5. }

localization

I18nPlugin npm

  1. new I18nPlugin(translations: Object, fnName = "__": String)

Create bundles with translations baked in. Then you can serve the translated bundle to your clients.

debugging

SourceMapDevToolPlugin

  1. new webpack.SourceMapDevToolPlugin({
  2. // asset matching
  3. test: string | RegExp | Array,
  4. include: string | RegExp | Array,
  5. exclude: string | RegExp | Array,
  6. // file and reference
  7. filename: string,
  8. append: false | string,
  9. // sources naming
  10. moduleFilenameTemplate: string,
  11. fallbackModuleFilenameTemplate: string,
  12. // quality/performance
  13. module: bool,
  14. columns: bool,
  15. lineToLine: bool | object
  16. })

Adds SourceMaps for assets.

test, include and exclude are used to determine which assets should be processed. Each one can be a RegExp (asset filename is matched), a string (asset filename need to start with this string) or a Array of those (any of them need to be matched). test defaults to .js files if omitted.

filename defines the output filename of the SourceMap. If no value is provided the SourceMap is inlined.

append is appended to the original asset. Usually the #sourceMappingURL comment. [url] is replaced with a URL to the SourceMap file. false disables the appending.

moduleFilenameTemplate and fallbackModuleFilenameTemplate see output.devtoolModuleFilenameTemplate.

module (defaults to true) When false loaders do not generate SourceMaps and the transformed code is used as source instead.

columns (defaults to true) When false column mappings in SorceMaps are ignored and a faster SourceMap implementation is used.

lineToLine (an object {test, include, exclude} which is matched against modules) matched modules uses simple (faster) line to line source mappings.

other

HotModuleReplacementPlugin

  1. new webpack.HotModuleReplacementPlugin()

Enables Hot Module Replacement. (This requires records data if not in dev-server mode, recordsPath)

Generates Hot Update Chunks of each chunk in the records. It also enables the [[API | hot-module-replacement]] and makes __webpack_hash__ available in the bundle.

ExtendedAPIPlugin

  1. new webpack.ExtendedAPIPlugin()

Adds useful free vars to the bundle.

__webpack_hash__ The hash of the compilation available as free var.

WARNING: Don’t combine it with the HotModuleReplacementPlugin. It would break and you don’t need it as the HotModuleReplacementPlugin export the same stuff.

NoErrorsPlugin

  1. new webpack.NoErrorsPlugin()

When there are errors while compiling this plugin skips the emitting phase (and recording phase), so there are no assets emitted that include errors. The emitted flag in the stats is false for all assets. If you are using the CLI, the webpack process will not exit with an error code by enabling this plugin. If you want webpack to “fail” when using the CLI, please check out the bail option.

ProgressPlugin

  1. new webpack.ProgressPlugin(function handler(percentage, msg) {/* ... */})

Hook into the compiler to extract progress information. The handler must have the signature function(percentage, message). It’s called with 0 <= percentage <= 1. percentage == 0 indicates the start. percentage == 1 indicates the end.

WatchIgnorePlugin

  1. new webpack.WatchIgnorePlugin(paths)

Does not watch specified files matching provided paths or RegExps.

  • paths (array) an array of RegExps or absolute paths to directories or files to test against

HtmlWebpackPlugin npm

  1. HtmlWebpackPlugin = require('html-webpack-plugin');
  2. new HtmlWebpackPlugin({ title: 'Webpack App' })

Generates a solid base html page for your web application with all your webpack generated css and js files built in.
Supports custom templates, favicon, html-minifications and more:

S3Plugin npm

  1. S3Plugin = require('webpack-s3-plugin')
  2. new S3Plugin({
  3. exclude: RegExp,
  4. s3Options: {
  5. accessKeyId: string,
  6. secretAccessKey: string,
  7. region: string
  8. },
  9. s3UploadOptions: {
  10. Bucket: string
  11. },
  12. cdnizerOptions: {
  13. defaultCDNBase: string
  14. }
  15. })

Uploads your content to s3. Can also run your html files through cdnizer to change the url to match

BellOnBundlerErrorPlugin npm

  1. var BellOnBundlerErrorPlugin = require('bell-on-bundler-error-plugin')
  2. {
  3. plugins: [
  4. new BellOnBundlerErrorPlugin()
  5. ]
  6. }

Get notification on bundler build errors. On that occasion, a bell character will be written to STDERR output.

WebpackShellPlugin npm

  1. const WebpackShellPlugin = require('webpack-shell-plugin');
  2. var plugins = [];
  3. {
  4. plugins: [
  5. new WebpackShellPlugin({
  6. onBuildStart: ['echo "Starting"'],
  7. onBuildEnd: ['python pi.py', 'node openBrowser.js', 'haxe game.hx && ssh -i /myPems/key.pem BObama@healthcare.gov']
  8. })
  9. ]
  10. }

Fires shell commands before and after webpack builds. Great for reporting tools, testing, or opening your browser for development. Learn more.

WebpackAngularResourcePlugin

  1. In the entry point where the main AngularJS module is defined:
  2. var angularResourceUtil = require('webpack-angular-resource-plugin');
  3. Require all css files under the current directory and its subdirectories:
  4. var styleContext = require.context(".", true, /.css$/);
  5. angularResourceUtil.requireAll(styleContext);
  6. Define the main Angular module. Also require all files whose name end with .controller.js which contain submodules. Notice that the module names are returned as an array and passed to the factory method as dependencies of the main module:
  7. var controllerContext = require.context('.', true, /\.controller\.js$/)
  8. module.exports = {
  9. default:angular.module('app', angularResourceUtil.requireAll(controllerContext))
  10. }

Require all AngularJS modules for a Webpack project and return an array of the module names that can be used as dependencies of the main module. Can also batch require other resources such as style sheets and images. Learn more.