插件列表

配置

NormalModuleReplacementPlugin

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

new webpack.ContextReplacementPlugin(
                resourceRegExp, 
                [newContentResource],
                [newContentRecursive],
                [newContentRegExp])

Replaces the default resource, recursive flag or regExp generated by parsing with newContentResource, newContentRecursive resp. newContextRegExp if the resource (directory) matches resourceRegExp. 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

new webpack.IgnorePlugin(requestRegExp, [contextRegExp])

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

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

PrefetchPlugin

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

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:

new webpack.ResolverPlugin([
    new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
], ["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:

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

输出

BannerPlugin

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.

优化

DedupePlugin

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 is experimental and may crash, because of some missing implementations. (Report an issue)

LimitChunkCountPlugin

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

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

OccurenceOrderPlugin

new webpack.optimize.OccurenceOrderPlugin(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

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.

new webpack.optimize.UglifyJsPlugin({
    compress: {
        warnings: false
    }
})

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 false. But you can configure the plugin to avoid mangling specific variable names by passing an except list:

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

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

ngAnnotatePlugin

new ngAnnotatePlugin([options]);

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

CommonsChunkPlugin

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 asnyc 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.

new CommonsChunkPlugin({
  name: "commons",
  // (the commons chunk name)

  filename: "commons.js",
  // (the filename of the commons chunk)

  // minChunks: 3,
  // (Modules must be shared between 3 entries)

  // chunks: ["pageA", "pageB"],
  // (Only use these entries)
})

You must load the generated chunk before the entry point:

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

2. Explicit vendor chunk

Split your code into vendor and application.

entry: {
  vendor: ["jquery", "other-lib"],
  app: "./entry"
}
new CommonsChunkPlugin({
  name: "vendor",

  // filename: "vendor.js"
  // (Give the chunk a different name)

  minChunks: Infinity,
  // (with more entries, this ensures that no other module
  //  goes into the vendor chunk)
})
<script src="vendor.js" charset="utf-8"></script>
<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).

new CommonsChunkPlugin({
  // names: ["app", "subPageA"]
  // (choose the chunks, or omit for all chunks)

  children: true,
  // (select all children of chosen chunks)

  // minChunks: 3,
  // (3 children must share the module before it's moved)
})

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.

new CommonsChunkPlugin({
  // names: ["app", "subPageA"]
  // (choose the chunks, or omit for all chunks)

  children: true,
  // (use all children of the chunk)

  async: true,
  // (create an async commons chunk)

  // minChunks: 3,
  // (3 children must share the module before it's separated)
})

AggressiveMergingPlugin

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.

AppCachePlugin

Generates a HTML5 Application Cache manifest

OfflinePlugin

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

new webpack.dependencies.LabeledModulesPlugin()

Support Labeled Modules.

ComponentPlugin

Use component with webpack.

AngularPlugin

Use angular.js modules with webpack.

dependency injection

DefinePlugin

new webpack.DefinePlugin(definitions)

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

Example:

new webpack.DefinePlugin({
    VERSION: JSON.stringify("5fa3b9"),
    BROWSER_SUPPORTS_HTML5: true,
    TWO: "1+1",
    "typeof window": JSON.stringify("object")
})
console.log("Running App version " + VERSION);
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:

if(DEBUG)
    console.log('Debug info')
if(PRODUCTION)
    console.log('Production log')
``

After passing through webpack with no minification results in:

if(false)
    console.log('Debug info')
if(true)
    console.log('Production log')
``

and then after a minification pass results in:

console.log('Production log')
``

ProvidePlugin

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:

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

RewirePlugin

Use rewire in webpack.

NgRequirePlugin

Automatically require AngularJS modules without explicitly write require statement.

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

本地化

I18nPlugin

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

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

调试

SourceMapDevToolPlugin

new webpack.SourceMapDevToolPlugin({
  // asset matching
  test: string | RegExp | Array,
  include: string | RegExp | Array,
  exclude: string | RegExp | Array,

  // file and reference
  filename: string,
  append: bool | string,

  // sources naming
  moduleFilenameTemplate: string,
  fallbackModuleFilenameTemplate: string,

  // quality/performance
  module: bool,
  columns: bool,
  lineToLine: bool | object
})

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

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

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

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.

WatchIgnorePlugin

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

S3Plugin

new S3Plugin({
  exclude: RegExp,
  s3Options: {
    accessKeyId: string,
    secretAccessKey: string,
    region: string
  },
  s3UploadOptions: {
    Bucket: string
  },
  cdnizerConfig: {
    defaultCDNBase: string
  }
})

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