- Notifications
You must be signed in to change notification settings - Fork125
list of plugins
newwebpack.NormalModuleReplacementPlugin(resourceRegExp,newResource)
Replace resources that matchresourceRegExp withnewResource. IfnewResource is relative, it is resolved relative to the previous resource.IfnewResource is a function, it is expected to overwrite the 'request' attribute of the supplied object.
newwebpack.ContextReplacementPlugin(resourceRegExp,[newContentResource],[newContentRecursive],[newContentRegExp])
If the resource (directory) matchesresourceRegExp, the plugin replaces the default resource, recursive flag or regExp generated by parsing withnewContentResource,newContentRecursive ornewContextRegExp respectively. IfnewContentResource is relative, it is resolved relative to the previous resource.IfnewContentResource is a function, it is expected to overwrite the 'request' attribute of the supplied object.
newwebpack.IgnorePlugin(requestRegExp,[contextRegExp])
Don't generate modules for requests matching the provided RegExp.
requestRegExpA RegExp to test the request against.contextRegExp(optional) A RegExp to test the context (directory) against.
newwebpack.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 an absolute path to a directory
request a request string for a normal module
newwebpack.ResolverPlugin(plugins,[types])
Apply a plugin (or array ofplugins) to one or more resolvers (as specified intypes).
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 fromenhanced-resolve are exported as properties for theResolverPlugin.
Example:
newwebpack.ResolverPlugin([newwebpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json",["main"])],["normal","loader"])
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:
newwebpack.ResolverPlugin([newwebpack.ResolverPlugin.FileAppendPlugin(['/dist/compiled-moduled.js'])])
This plugin will allow you to reference environment variables through process.env
newwebpack.EnvironmentPlugin(["NODE_ENV"])
In your code:
varenv=process.env.NODE_ENV;
newDotenvWebpack([options]);
Wrapsdotenv to include environment variables in your bundle. Only includesexplicitly defined variables in the final bundle.
newRawBundlerPlugin({bundles:["vendor.js"],"vendor.js":['js/*.js']})
Merges your files, unedited, into a single file. See repo for a full list of options.
newwebpack.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.
newwebpack.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 instances. They won't be one instance after deduplication.
Note: Don't use it in watch mode. Only for production builds.
Note:DedupePlugin has been removed since Webpack 2. Using this plugin will throw an error.
newwebpack.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)
newwebpack.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
newwebpack.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 total file size and is recommended.
preferEntry (boolean) give entry chunks higher priority. This makes entry chunks smaller but increases the overall size. (recommended)
newwebpack.optimize.UglifyJsPlugin([options])
Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode. You can pass an object containingUglifyJS options.
newwebpack.optimize.UglifyJsPlugin({compress:{warnings:false}})
UglifyJS options:
compress(boolean|object): options for UglifyJS compression, which is enabled by default - see theCompressorsource for options and defaults.Use
compress: falseto explicitly disable compression.mangle(boolean|object): options for UglifyJS variable name mangling, which is enabled by default - see_default_mangler_optionsin UglifyJS' source for options and defaults.Use
mangle: falseto explicitly disable mangling.mangle.props(boolean|object): passingtrueor an object enables and provides options for UglifyJS property mangling - seeUglifyJS documentation formanglePropertiesfor options.Note: the UglifyJS docs warn thatyou will probably break your source if you use property mangling, so if you aren't sure why you'd need this feature, you most likely shouldn't be using it!
output: an object providing options for UglifyJS'OutputStream- see theOutputStreamsource for options and defaults.
Additional options:
beautify(boolean): set totrueto enable UglifyJS output beautification.If
beautifyconfig is also provided in anoutputobject, it will override this configuration.comments(boolean|RegExp|function(astNode, comment) -> boolean): configure preservation of comments in output.Defaults to preserving comments containing
/*!,/**!,@preserveor@license.If
commentsconfig is also provided in anoutputobject, it will override this configuration.sourceMap(boolean): use SourceMaps to map error message locations to modules. This slows down the compilation. (default:true)test,include,exclude(RegExp|Array<RegExp>): configure filtering of 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:
new webpack.optimize.UglifyJsPlugin({ mangle: { except: ['$super', '$', 'exports', 'require'] }})With this, the plugin will not mangle any occurrence of$super,$,exports orrequire.
newngAnnotatePlugin([options]);
Runs theng-annotate pre-minimizer to insert AngularJS dependency injection annotations.
newwebpack.optimize.CommonsChunkPlugin(options)
options.nameoroptions.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 andoptions.asyncoroptions.childrenis set all chunks are used, otherwiseoptions.filenameis used as chunk name.options.filename(string): The filename template for the commons chunk. Can contain the same placeholder asoutput.filename. If omitted the original filename is not modified (usuallyoutput.filenameoroutput.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. PassingInfinityjust creates the commons chunk but moves no modules into it. By providing afunctionyou 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): Iftrueall children of the commons chunk are selectedoptions.async(boolean|string): Iftruea new async commons chunk is created as a child ofoptions.nameand sibling ofoptions.chunks. It is loaded in parallel withoptions.chunks. It is possible to change the name of the output file by providing the desired string instead oftrue.options.minSize(number): Minimum size of all common module before a commons chunk is created.
Examples:
Generate an extra chunk, which contains common modules shared between entry points.
newCommonsChunkPlugin({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:
<scriptsrc="commons.js"charset="utf-8"></script><scriptsrc="entry.bundle.js"charset="utf-8"></script>
Split your code into vendor and application.
entry:{vendor:["jquery","other-lib"],app:"./entry"}newCommonsChunkPlugin({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)})
<scriptsrc="vendor.js"charset="utf-8"></script><scriptsrc="app.js"charset="utf-8"></script>
Hint: In combination with long-term caching you may need to usethis plugin to avoid that the vendor chunk changes. You should also use records to ensure stable module ids.
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 needs to download many sibling chunks).
newCommonsChunkPlugin({// 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)})
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.
newCommonsChunkPlugin({// 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)})
newwebpack.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 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 minimally required size reduction for chunk merging. Defaults to1.5 which means that the total size needs to be reduced 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 tofalse.
options.entryChunkMultiplicator Whenoptions.moveToParents is set, moving to an entry chunk is more expensive. Defaults to10, which means moving to an entry chunk is ten times more expensive than moving to a normal chunk.
Output "dll" bundles. Dll bundles don'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 plugin withoutput.library option to expose the dll function i. e. into the global scope.
newDllPlugin({path:path.join(__dirname,"manifest.json"),name:"[name]_[hash]",context:__dirname})
path:absolute path to the manifest json file (output)name: name of the exposed dll function (keep consistent withoutput.library)context(optional): context of requests in the manifest file, defaults to the webpack context
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 theDllPlugin.
Can be used in two different modes:
Scoped mode
The content of the dll is accessible under a module prefix. i. e. withscope = "xyz" a fileabc in the dll can be access viarequire("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 containsjquery and the fileabc,require("jquery") andrequire("./abc") will be used from the dll.
newDllReferencePlugin({context:__dirname,scope:"xyz",manifest:require("./manifest.json"),name:"./my-dll.js",sourceType:"commonsjs2",content:{ ...}})
context: (absolute path) context of requests in the manifest (or content property)scope(optional): prefix which is used for accessing the content of the dllmanifest(object): an object containingcontentandnamename(optional): the name where the dll is exposed (defaults tomanifest.name) (see alsoexternals)sourceType(optional): the type how the dll is exposed (defaults to"var") (see alsoexternals)content(optional): the mappings from request to module id (defaults tomanifest.content)
Dll bundle:output.library = "[name]_[hash]"output.libraryTarget = "var"DllPlugin.name = "[name]_[hash]"
Dll consumer:DllReferencePlugin.sourceType = "var"
Dll bundle:output.libraryTarget = "commonjs2"
Dll consumer:DllReferencePlugin.sourceType = "commonjs2"DllReferencePlugin.name = "./path/to/dll.js"
Generates a HTML5 Application Cache manifest
Plugin which brings offline support to your project. It generatesServiceWorker based on output files and chosen update strategy.AppCache is used as a fallback whenServiceWorker is not available.
Use a service worker to cache all your bundles' emitted assets. This plugin will generate a service worker file usingsw-precache then add it to your build directory. You can optionally pass your ownsw-precache config options.
Compresses and optimizes your images usingImagemin. Unlikeimage-webpack-loader this will also optimize images from plugins likefavicons-webpack-plugin.
newwebpack.dependencies.LabeledModulesPlugin()
Support Labeled Modules.
Use angular.js modules with webpack.
newwebpack.DefinePlugin(definitions)
The DefinePlugin allows you to create global constants which can be configured atcompile time. This can be very useful for allowing different behavior between development builds and release builds. For example, you might use a global constant to determine whether logging takes place; perhaps you perform logging in your development build but not in the release build. That's the sort of scenario the DefinePlugin facilitates.
Example:
newwebpack.DefinePlugin({PRODUCTION:JSON.stringify(true),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 intoDefinePlugin 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
typeofto 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(!PRODUCTION)console.log('Debug info')if(PRODUCTION)console.log('Production log')
After passing through webpack with no minification results in:
if(!true)console.log('Debug info')if(true)console.log('Production log')
and then after a minification pass results in:
console.log('Production log')
newwebpack.ProvidePlugin(definitions)
Automatically loaded modules. Module (value) is loaded when the identifier (key) is used as a free variable in a module. The identifier is filled with the exports of the loaded module.
Example:
newwebpack.ProvidePlugin({$:"jquery"})
// in a module$("#item")// <= just works// $ is automatically set to the exports of module "jquery"
Userewire in webpack.
Automatically require AngularJS modules without explicitly writerequire statement.
{plugins:[newngRequirePlugin(['file path list for your angular modules. eg: src/**/*.js'])]}
newI18nPlugin(translations:Object,fnName="__":String)
Create bundles with translations baked in. Then you can serve the translated bundle to your clients.
newwebpack.SourceMapDevToolPlugin({// asset matchingtest:string|RegExp|Array,include:string|RegExp|Array,exclude:string|RegExp|Array,// file and referencefilename:string,append:false|string,// sources namingmoduleFilenameTemplate:string,fallbackModuleFilenameTemplate:string,// quality/performancemodule:bool,columns:bool,lineToLine:bool|object})
Adds SourceMaps for assets.
test,include andexclude 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 an 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 andfallbackModuleFilenameTemplate seeoutput.devtoolModuleFilenameTemplate.
module (defaults totrue) Whenfalse loaders do not generate SourceMaps and the transformed code is used as source instead.
columns (defaults totrue) Whenfalse column mappings in SourceMaps 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.
newwebpack.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 theAPI and makes__webpack_hash__ available in the bundle.
newwebpack.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 theHotModuleReplacementPluginexport the same stuff.
newwebpack.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. Theemitted flag in the stats isfalse for all assets. If you are using the CLI, the webpack process willnot exit with an error code by enabling this plugin. If you want webpack to "fail" when using the CLI, please check out thebail option.
newwebpack.ProgressPlugin(functionhandler(percentage,msg){/* ... */})
Hook into the compiler to extract progress information. Thehandler must have the signaturefunction(percentage, message). It's called with0 <= percentage <= 1.percentage == 0 indicates the start.percentage == 1 indicates the end.
newwebpack.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=require('html-webpack-plugin');newHtmlWebpackPlugin({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:
Provide a series of paths to be rendered by executing your Webpack-compiled render function, allowing universal rendering techniques to be used at build time.
varStaticSiteGeneratorPlugin=require('static-site-generator-webpack-plugin');varpaths=['/','/blog/','/blog/hello-world/', ...];entry:{'static-render':'./static-render.js'},output:{filename:'static-render.js',path:'dist',/* You must compile to UMD or CommonJS * so it can be required in a Node context: */libraryTarget:'umd'},plugins:[newStaticSiteGeneratorPlugin('static-render',paths)]
S3Plugin=require('webpack-s3-plugin')newS3Plugin({exclude:RegExp,s3Options:{accessKeyId:string,secretAccessKey:string,region:string},s3UploadOptions:{Bucket:string},cdnizerOptions:{defaultCDNBase:string}})
Uploads your content to s3. Can also run your html files throughcdnizer to change the URL to match
varBellOnBundlerErrorPlugin=require('bell-on-bundler-error-plugin'){plugins:[newBellOnBundlerErrorPlugin()]}
Get a notification of bundler build errors. On that occasion, a bell character will be written to STDERR output.
// webpack.config.jsvarWebpackBuildNotifierPlugin=require('webpack-build-notifier');module.exports={// ... snip ...plugins:[newWebpackBuildNotifierPlugin({title:"My Project Webpack Build",logo:path.resolve("./img/favicon.png"),suppressSuccess:true})],// ... snip ...}
A plugin which displays OS-level notifications for Webpack build errors and warnings.
constWebpackShellPlugin=require('webpack-shell-plugin');varplugins=[];{plugins:[newWebpackShellPlugin({onBuildStart:['echo "Starting"'],onBuildEnd:['python pi.py','node openBrowser.js','haxe game.hx && ssh -i /myPems/key.pem BObama@healthcare.gov']})]}
Fires shell commands before and after webpack builds. Great for reporting tools, testing, or opening your browser for development. Learnmore.
IntheentrypointwherethemainAngularJSmoduleis defined:varangularResourceUtil=require('webpack-angular-resource-plugin');Requireallcssfilesunderthecurrentdirectoryandits subdirectories:varstyleContext=require.context(".",true,/.css$/);angularResourceUtil.requireAll(styleContext);DefinethemainAngularmodule.Also,requireallfileswhosenameendwith.controller.jswhichcontainsubmodules.Noticethatthemodulenamesarereturnedasanarrayandpassedtothefactorymethodasdependenciesofthemain module:varcontrollerContext=require.context('.',true,/\.controller\.js$/)module.exports={default:angular.module('app',angularResourceUtil.requireAll(controllerContext))}
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. Learnmore.
constWebpackBrowserPlugin=require('webpack-browser-plugin');varplugins=[];{ plugins:[newWebpackBrowserPlugin();]}
Automatically opens a browser to your application after webpack or webpack-dev-server completes. If webpack is used, browser-sync is used to launch your build. Learnmore.
constFaviconsWebpackPlugin=require('favicons-webpack-plugin');varplugins=[];{plugins:[newFaviconsWebpackPlugin('my-logo.png')]}
Automatically generates over 30 favicons (configurable) for Android, iOS, and the different desktop browsers from one source png. Integrates well with the html-webpack-plugin.
constpath=require('path');constWebpackPluginGraphqlSchemaHot=require('webpack-plugin-graphql-schema-hot');varplugins=[];{plugins:[newWebpackPluginGraphqlSchemaHot({schemaPath:path.resolve(__dirname,'../schema/index.js'),output:{json:path.resolve(__dirname,'../build/schema.graphql.json'),txt:path.resolve(__dirname,'../build/schema.graphql.txt'),},runOnStart:true,verbose:true,hideErrors:false,}),]}
This plugin tracks changes in your GraphQL Schema and generates its introspection injson andtxt formats.
constfilewatcherPlugin=require('filewatcher-webpack-plugin');varplugins=[];{plugins:[newfilewatcherPlugin({watchFileRegex:['../scriptFolder/**/*.js','../stylesheets/**/*.css']})]}
This plugin watches files/folders not under Webpack watch. Accepts glob pattern. Turbo powered bychokidar. Here we are watching "all files contained in folder namedscriptFolder andstylesheets (or any nested folder inside it) having extension .js or .css respectively"..
constNodeSecurityPlugin=require('webpack-nodesecurity-plugin');varplugins=[];{plugins:[newNodeSecurityPlugin()]}
Webpack plugin that runs the Node Security Platform audit on your package.json, package-lock.json or npm-shrinkwrap.json.
It is a wrapper for thenodesecurity/nsp package.
webpack 👍