The people who contribute to webpack do so for the love of open source, our users and ecosystem, and most importantly, pushing the web forward together. Because of our Open Collective model for funding and transparency, we are able to funnel support and funds through contributors, dependent projects, and the contributor and core teams. To make a donation, click the button below...
But what is the return on the investment?
The biggest core feature we'd like to provide is an enjoyable development experience. Developers like you can help by contributing to rich and vibrant documentation, issuing pull requests to help us cover niche use cases, and to help sustain what you love about webpack.
Anybody can help by doing any of the following:
You can ask your employer to improve your workflow by leveraging webpack: an all-in-one tool for fonts, images and image optimization, and json. Explain to them how webpack will attempt to bundle your code and assets the best it can for the smallest file size, leading to speedier sites and applications.
Contributing to webpack is not contributing to an exclusive club. You as a developer are contributing to the overall health of downstream projects. Hundreds, if not thousands, of projects depend on webpack and contributing will make the ecosystem better for all the users.
The remainder of this section of the site is dedicated to developers such as yourself who would like to become a part of our ever-growing community:
CTO's, VPs, and owners can help too!
Webpack is an all-in-one tool for bundling your code. It can handle fonts, images, data and more with the help of community-driven plugins and loaders. Having all of your assets be handled by one tool is immensely helpful, as you or your team can spend less time making sure a machine with many moving parts is working correctly and more time building your product.
Aside from monetary assistance, companies can support webpack by:
You can also encourage your developers to contribute to the ecosystem by open-sourcing webpack loaders, plugins and other utilities. And, as mentioned above, we would greatly appreciate any help in increasing our CI/CD infrastructure.
To anyone else who is interested in helping our mission – e.g. venture capitalists, government entities, digital agencies, etc. – we would love for you to work with us, one of the top npm packages, to improve your product! Please don't hesitate to reach out with questions.
Documentation of webpack features and changes is now being updated as webpack evolves. An automated issue creation integration was established and proven to be effective in the recent years. When a feature gets merged, an issue with a documentation request is created in our repository and we expect to resolve it in a timely manner. This means that there are features, changes and breaking changes awaiting to be documented, reviewed and released. That said, if Pull Request's author is abandoning it for more than 30 days, we may mark such Pull Request as stale. We may take over the work that is needed to finish it. If Pull Request author grants write access to their fork to the webpack Documentation team we will commit directly to your branch and finish the work. In other cases, we may have to start over by ourselves or by delegating it to willing community members. This may render your Pull Request redundant and it might get closed as a part of the cleanup process.
The following sections contain all you need to know about editing and formatting the content within this site. Make sure to do some research before starting your edits or additions. Sometimes the toughest part is finding where the content should live and determining whether or not it already exists.
edit
and expand on the structure.Each article contains a small section at the top written in YAML Frontmatter:
---
title: My Article
group: My Sub-Section
sort: 3
contributors:
- [github username]
related:
- title: Title of Related Article
url: [url of related article]
---
Let's break these down:
title
: The name of the article.group
: The name of the sub-sectionsort
: The order of the article within its section (or) sub-section if it is present.contributors
: A list of GitHub usernames who have contributed to this article.related
: Any related reading or useful examples.Note that related
will generate a Further Reading section at the bottom of the page and contributors
will yield a Contributors section below it. If you edit an article and would like recognition, don't hesitate to add your GitHub username to the contributors
list.
css-loader
, ts-loader
, …BannerPlugin
, NpmInstallWebpackPlugin
, …Syntax: ```javascript … ```
function foo() {
return 'bar';
}
foo();
Use single quotes in code snippets and project files (.jsx
, .scss
etc):
- import webpack from "webpack";
+ import webpack from 'webpack';
And in inline backticks:
correct
Set value to 'index.md'
...
incorrect
Set value to "index.md"
...
Lists should be ordered alphabetically.
Parameter | Explanation | Input Type | Default Value |
---|---|---|---|
--debug | Switch loaders to debug mode | boolean | false |
--devtool | Define source map type for the bundled resources | string | - |
--progress | Print compilation progress in percentage | boolean | false |
Tables should also be ordered alphabetically.
The configuration properties should be ordered alphabetically as well:
devServer.compress
devServer.hot
devServer.static
Syntax: >
This is a blockquote.
Syntax: T>
Syntax: W>
Syntax: ?>
Do not make assumptions when writing the documentation.
- You might already know how to optimize bundle for production...
+ As we've learned in [production guide](/guides/production/)...
Please do not assume things are simple. Avoid words like 'just', 'simply'.
- Simply run command...
+ Run the `command-name` command...
Always provide types and defaults to all of the documentation options in order to keep the documentation accessible and well-written. We are adding types and defaults after entitling the documented option:
configuration.example.option
string = 'none'
Where = 'none'
means that the default value is 'none'
for the given option.
string = 'none': 'none' | 'development' | 'production'
Where : 'none' | 'development' | 'production'
enumerates the possible type values, in this case, three strings are acceptable: 'none'
, 'development'
, and 'production'
.
Use space between types to list all available types for the given option:
string = 'none': 'none' | 'development' | 'production'
boolean
To mark an array, use square brackets:
string
[string]
If multiple types are allowed in array
, use comma:
string
[string, RegExp, function(arg) => string]
To mark a function, also list arguments when they are available:
function (compilation, module, path) => boolean
Where (compilation, module, path)
lists the arguments that the provided function will receive and => boolean
means that the return value of the function must be a boolean
.
To mark a Plugin as an available option value type, use the camel case title of the Plugin
:
TerserPlugin
[TerserPlugin]
Which means that the option expects one or few TerserPlugin
instances.
To mark a number, use number
:
number = 15: 5, 15, 30
To mark an object, use object
:
object = { prop1 string = 'none': 'none' | 'development' | 'production', prop2 boolean = false, prop3 function (module) => string }
When object's key can have multiple types, use |
to list them. Here is an example, where prop1
can be both a string and an array of strings:
object = { prop1 string = 'none': 'none' | 'development' | 'production' | [string]}
This allows us to display the defaults, enumeration and other information.
If the object's key is dynamic, user-defined, use <key>
to describe it:
object = { <key> string }
Sometimes, we want to describe certain properties of objects and functions in lists. When applicable add typing directly to the list where properties are enlisted:
madeUp
(boolean = true
): short descriptionshortText
(string = 'i am text'
): another short descriptionAn example can be found on the options
section of the EvalSourceMapDevToolPlugin's page.
Please use relative URLs (such as /concepts/mode/
) to link our own content instead of absolute URLs (such as https://webpack.js.org/concepts/mode/
).
A loader is a node module that exports a function. This function is called when a resource should be transformed by this loader. The given function will have access to the Loader API using the this
context provided to it.
Before we dig into the different types of loaders, their usage, and examples, let's take a look at the three ways you can develop and test a loader locally.
To test a single loader, you can use path
to resolve
a local file within a rule object:
webpack.config.js
const path = require('path');
module.exports = {
//...
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: path.resolve('path/to/loader.js'),
options: {
/* ... */
},
},
],
},
],
},
};
To test multiple, you can utilize the resolveLoader.modules
configuration to update where webpack will search for loaders. For example, if you had a local /loaders
directory in your project:
webpack.config.js
const path = require('path');
module.exports = {
//...
resolveLoader: {
modules: ['node_modules', path.resolve(__dirname, 'loaders')],
},
};
By the way, if you've already created a separate repository and package for your loader, you could npm link
it to the project in which you'd like to test it out.
When a single loader is applied to the resource, the loader is called with only one parameter – a string containing the content of the resource file.
Synchronous loaders can return
a single value representing the transformed module. In more complex cases, the loader can return any number of values by using the this.callback(err, values...)
function. Errors are either passed to the this.callback
function or thrown in a sync loader.
The loader is expected to give back one or two values. The first value is a resulting JavaScript code as string or buffer. The second optional value is a SourceMap as JavaScript object.
When multiple loaders are chained, it is important to remember that they are executed in reverse order – either right to left or bottom to top depending on array format.
In the following example, the foo-loader
would be passed the raw resource and the bar-loader
would receive the output of the foo-loader
and return the final transformed module and a source map if necessary.
webpack.config.js
module.exports = {
//...
module: {
rules: [
{
test: /\.js/,
use: ['bar-loader', 'foo-loader'],
},
],
},
};
The following guidelines should be followed when writing a loader. They are ordered in terms of importance and some only apply in certain scenarios, read the detailed sections that follow for more information.
Loaders should do only a single task. This not only makes the job of maintaining each loader easier, but also allows them to be chained for usage in more scenarios.
Take advantage of the fact that loaders can be chained together. Instead of writing a single loader that tackles five tasks, write five simpler loaders that divide this effort. Isolating them not only keeps each individual loader simple, but may allow for them to be used for something you hadn't thought of originally.
Take the case of rendering a template file with data specified via loader options or query parameters. It could be written as a single loader that compiles the template from source, executes it and returns a module that exports a string containing the HTML code. However, in accordance with guidelines, an apply-loader
exists that can be chained with other open source loaders:
pug-loader
: Convert template to a module that exports a function.apply-loader
: Executes the function with loader options and returns raw HTML.html-loader
: Accepts HTML and outputs a valid JavaScript module.Keep the output modular. Loader generated modules should respect the same design principles as normal modules.
Make sure the loader does not retain state between module transformations. Each run should always be independent of other compiled modules as well as previous compilations of the same module.
Take advantage of the loader-utils
package which provides a variety of useful tools. Along with loader-utils
, the schema-utils
package should be used for consistent JSON Schema based validation of loader options. Here's a brief example that utilizes both:
loader.js
import { urlToRequest } from 'loader-utils';
import { validate } from 'schema-utils';
const schema = {
type: 'object',
properties: {
test: {
type: 'string',
},
},
};
export default function (source) {
const options = this.getOptions();
validate(schema, options, {
name: 'Example Loader',
baseDataPath: 'options',
});
console.log('The request path', urlToRequest(this.resourcePath));
// Apply some transformations to the source...
return `export default ${JSON.stringify(source)}`;
}
In webpack, loaders can be chained together and share data with subsequent loaders in the chain. To achieve this, you can pass data along with the content (source code) using the this.callback
method in raw loaders. In the default exported function of a raw loader, you can pass data using the fourth argument of this.callback
.
export default function (source) {
const options = getOptions(this);
// Pass data using the fourth argument of this.callback
this.callback(null, `export default ${JSON.stringify(source)}`, null, {
some: data,
});
}
In the example above, some
property in the fourth argument of this.callback
is used to pass data to the next chained loader.
If a loader uses external resources (i.e. by reading from filesystem), they must indicate it. This information is used to invalidate cacheable loaders and recompile in watch mode. Here's a brief example of how to accomplish this using the addDependency
method:
loader.js
import path from 'path';
export default function (source) {
var callback = this.async();
var headerPath = path.resolve('header.js');
this.addDependency(headerPath);
fs.readFile(headerPath, 'utf-8', function (err, header) {
if (err) return callback(err);
callback(null, header + '\n' + source);
});
}
Depending on the type of module, there may be a different schema used to specify dependencies. In CSS for example, the @import
and url(...)
statements are used. These dependencies should be resolved by the module system.
This can be done in one of two ways:
require
statements.this.resolve
function to resolve the path.The css-loader
is a good example of the first approach. It transforms dependencies to require
s, by replacing @import
statements with a require
to the other stylesheet and url(...)
with a require
to the referenced file.
In the case of the less-loader
, it cannot transform each @import
to a require
because all .less
files must be compiled in one pass for variables and mixin tracking. Therefore, the less-loader
extends the less compiler with custom path resolving logic. It then takes advantage of the second approach, this.resolve
, to resolve the dependency through webpack.
Avoid generating common code in every module the loader processes. Instead, create a runtime file in the loader and generate a require
to that shared module:
src/loader-runtime.js
const { someOtherModule } = require('./some-other-module');
module.exports = function runtime(params) {
const x = params.y * 2;
return someOtherModule(params, x);
};
src/loader.js
import runtime from './loader-runtime.js';
export default function loader(source) {
// Custom loader logic
return `${runtime({
source,
y: Math.random(),
})}`;
}
Don't insert absolute paths into the module code as they break hashing when the root for the project is moved. You can use below code to convert absolute paths to relative ones.
// `loaderContext` is same as `this` inside loader function
JSON.stringify(
loaderContext.utils.contextify(
loaderContext.context || loaderContext.rootContext,
request
)
);
If the loader you're working on is a simple wrapper around another package, then you should include the package as a peerDependency
. This approach allows the application's developer to specify the exact version in the package.json
if desired.
For instance, the sass-loader
specifies node-sass
as peer dependency like so:
{
"peerDependencies": {
"node-sass": "^4.0.0"
}
}
So you've written a loader, followed the guidelines above, and have it set up to run locally. What's next? Let's go through a unit testing example to ensure our loader is working the way we expect. We'll be using the Jest framework to do this. We'll also install babel-jest
and some presets that will allow us to use the import
/ export
and async
/ await
. Let's start by installing and saving these as a devDependencies
:
npm install --save-dev jest babel-jest @babel/core @babel/preset-env
babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
Our loader will process .txt
files and replace any instance of [name]
with the name
option given to the loader. Then it will output a valid JavaScript module containing the text as its default export:
src/loader.js
export default function loader(source) {
const options = this.getOptions();
source = source.replace(/\[name\]/g, options.name);
return `export default ${JSON.stringify(source)}`;
}
We'll use this loader to process the following file:
test/example.txt
Hey [name]!
Pay close attention to this next step as we'll be using the Node.js API and memfs
to execute webpack. This lets us avoid emitting output
to disk and will give us access to the stats
data which we can use to grab our transformed module:
npm install --save-dev webpack memfs
test/compiler.js
import path from 'path';
import webpack from 'webpack';
import { createFsFromVolume, Volume } from 'memfs';
export default (fixture, options = {}) => {
const compiler = webpack({
context: __dirname,
entry: `./${fixture}`,
output: {
path: path.resolve(__dirname),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.txt$/,
use: {
loader: path.resolve(__dirname, '../src/loader.js'),
options,
},
},
],
},
});
compiler.outputFileSystem = createFsFromVolume(new Volume());
compiler.outputFileSystem.join = path.join.bind(path);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) reject(err);
if (stats.hasErrors()) reject(stats.toJson().errors);
resolve(stats);
});
});
};
And now, finally, we can write our test and add an npm script to run it:
test/loader.test.js
/**
* @jest-environment node
*/
import compiler from './compiler.js';
test('Inserts name and outputs JavaScript', async () => {
const stats = await compiler('example.txt', { name: 'Alice' });
const output = stats.toJson({ source: true }).modules[0].source;
expect(output).toBe('export default "Hey Alice!\\n"');
});
package.json
{
"scripts": {
"test": "jest"
},
"jest": {
"testEnvironment": "node"
}
}
With everything in place, we can run it and see if our new loader passes the test:
PASS test/loader.test.js
✓ Inserts name and outputs JavaScript (229ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.853s, estimated 2s
Ran all test suites.
It worked! At this point you should be ready to start developing, testing, and deploying your own loaders. We hope that you'll share your creations with the rest of the community!
Plugins expose the full potential of the webpack engine to third-party developers. Using staged build callbacks, developers can introduce their own behaviors into the webpack build process. Building plugins is a bit more advanced than building loaders, because you'll need to understand some of the webpack low-level internals to hook into them. Be prepared to read some source code!
A plugin for webpack consists of:
apply
method in its prototype.// A JavaScript class.
class MyExampleWebpackPlugin {
// Define `apply` as its prototype method which is supplied with compiler as its argument
apply(compiler) {
// Specify the event hook to attach to
compiler.hooks.emit.tapAsync(
'MyExampleWebpackPlugin',
(compilation, callback) => {
console.log('This is an example plugin!');
console.log(
'Here’s the `compilation` object which represents a single build of assets:',
compilation
);
// Manipulate the build using the plugin API provided by webpack
compilation.addModule(/* ... */);
callback();
}
);
}
}
Plugins are instantiated objects with an apply
method on their prototype. This apply
method is called once by the webpack compiler while installing the plugin. The apply
method is given a reference to the underlying webpack compiler, which grants access to compiler callbacks. A plugin is structured as follows:
class HelloWorldPlugin {
apply(compiler) {
compiler.hooks.done.tap(
'Hello World Plugin',
(
stats /* stats is passed as an argument when done hook is tapped. */
) => {
console.log('Hello World!');
}
);
}
}
module.exports = HelloWorldPlugin;
Then to use the plugin, include an instance in your webpack configuration plugins
array:
// webpack.config.js
var HelloWorldPlugin = require('hello-world');
module.exports = {
// ... configuration settings here ...
plugins: [new HelloWorldPlugin({ options: true })],
};
Use schema-utils
in order to validate the options being passed through the plugin options. Here is an example:
import { validate } from 'schema-utils';
// schema for options object
const schema = {
type: 'object',
properties: {
test: {
type: 'string',
},
},
};
export default class HelloWorldPlugin {
constructor(options = {}) {
validate(schema, options, {
name: 'Hello World Plugin',
baseDataPath: 'options',
});
}
apply(compiler) {}
}
Among the two most important resources while developing plugins are the compiler
and compilation
objects. Understanding their roles is an important first step in extending the webpack engine.
class HelloCompilationPlugin {
apply(compiler) {
// Tap into compilation hook which gives compilation as argument to the callback function
compiler.hooks.compilation.tap('HelloCompilationPlugin', (compilation) => {
// Now we can tap into various hooks available through compilation
compilation.hooks.optimize.tap('HelloCompilationPlugin', () => {
console.log('Assets are being optimized.');
});
});
}
}
module.exports = HelloCompilationPlugin;
For the list of hooks available on compiler
, compilation
, and other important objects, see the plugins API docs.
Some plugin hooks are asynchronous. To tap into them, we can use tap
method which will behave in synchronous manner or use one of tapAsync
method or tapPromise
method which are asynchronous methods.
When we use tapAsync
method to tap into plugins, we need to call the callback function which is supplied as the last argument to our function.
class HelloAsyncPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync(
'HelloAsyncPlugin',
(compilation, callback) => {
// Do something async...
setTimeout(function () {
console.log('Done with async work...');
callback();
}, 1000);
}
);
}
}
module.exports = HelloAsyncPlugin;
When we use tapPromise
method to tap into plugins, we need to return a promise which resolves when our asynchronous task is completed.
class HelloAsyncPlugin {
apply(compiler) {
compiler.hooks.emit.tapPromise('HelloAsyncPlugin', (compilation) => {
// return a Promise that resolves when we are done...
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log('Done with async work...');
resolve();
}, 1000);
});
});
}
}
module.exports = HelloAsyncPlugin;
Once we can latch onto the webpack compiler and each individual compilations, the possibilities become endless for what we can do with the engine itself. We can reformat existing files, create derivative files, or fabricate entirely new assets.
Let's write an example plugin that generates a new build file called assets.md
, the contents of which will list all of the asset files in our build. This plugin might look something like this:
class FileListPlugin {
static defaultOptions = {
outputFile: 'assets.md',
};
// Any options should be passed in the constructor of your plugin,
// (this is a public API of your plugin).
constructor(options = {}) {
// Applying user-specified options over the default options
// and making merged options further available to the plugin methods.
// You should probably validate all the options here as well.
this.options = { ...FileListPlugin.defaultOptions, ...options };
}
apply(compiler) {
const pluginName = FileListPlugin.name;
// webpack module instance can be accessed from the compiler object,
// this ensures that correct version of the module is used
// (do not require/import the webpack or any symbols from it directly).
const { webpack } = compiler;
// Compilation object gives us reference to some useful constants.
const { Compilation } = webpack;
// RawSource is one of the "sources" classes that should be used
// to represent asset sources in compilation.
const { RawSource } = webpack.sources;
// Tapping to the "thisCompilation" hook in order to further tap
// to the compilation process on an earlier stage.
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
// Tapping to the assets processing pipeline on a specific stage.
compilation.hooks.processAssets.tap(
{
name: pluginName,
// Using one of the later asset processing stages to ensure
// that all assets were already added to the compilation by other plugins.
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
},
(assets) => {
// "assets" is an object that contains all assets
// in the compilation, the keys of the object are pathnames of the assets
// and the values are file sources.
// Iterating over all the assets and
// generating content for our Markdown file.
const content =
'# In this build:\n\n' +
Object.keys(assets)
.map((filename) => `- ${filename}`)
.join('\n');
// Adding new asset to the compilation, so it would be automatically
// generated by the webpack in the output directory.
compilation.emitAsset(
this.options.outputFile,
new RawSource(content)
);
}
);
});
}
}
module.exports = { FileListPlugin };
webpack.config.js
const { FileListPlugin } = require('./file-list-plugin.js');
// Use the plugin in your webpack configuration:
module.exports = {
// …
plugins: [
// Adding the plugin with the default options
new FileListPlugin(),
// OR:
// You can choose to pass any supported options to it:
new FileListPlugin({
outputFile: 'my-assets.md',
}),
],
};
This will generate a markdown file with chosen name that looks like this:
# In this build:
- main.css
- main.js
- index.html
A plugin can be classified into types based on the event hooks it taps into. Every event hook is pre-defined as synchronous or asynchronous or waterfall or parallel hook and hook is called internally using call/callAsync method. The list of hooks that are supported or can be tapped into is generally specified in this.hooks
property.
For example:
this.hooks = {
shouldEmit: new SyncBailHook(['compilation']),
};
It represents that the only hook supported is shouldEmit
which is a hook of SyncBailHook
type and the only parameter which will be passed to any plugin that taps into shouldEmit
hook is compilation
.
Various types of hooks supported are :
SyncHook
new SyncHook([params])
tap
method.call(...params)
method.Bail Hooks
SyncBailHook[params]
tap
method.call(...params)
method.In these types of hooks, each of the plugin callbacks will be invoked one after the other with the specific args
. If any value is returned except undefined by any plugin, then that value is returned by hook and no further plugin callback is invoked. Many useful events like optimizeChunks
, optimizeChunkModules
are SyncBailHooks.
Waterfall Hooks
SyncWaterfallHook[params]
tap
method.call(...params)
methodHere each of the plugins is called one after the other with the arguments from the return value of the previous plugin. The plugin must take the order of its execution into account.
It must accept arguments from the previous plugin that was executed. The value for the first plugin is init
. Hence at least 1 param must be supplied for waterfall hooks. This pattern is used in the Tapable instances which are related to the webpack templates like ModuleTemplate
, ChunkTemplate
etc.
Async Series Hook
AsyncSeriesHook[params]
tap
/tapAsync
/tapPromise
method.callAsync(...params)
methodThe plugin handler functions are called with all arguments and a callback function with the signature (err?: Error) -> void
. The handler functions are called in order of registration. callback
is called after all the handlers are called.
This is also a commonly used pattern for events like emit
, run
.
Async waterfall The plugins will be applied asynchronously in the waterfall manner.
AsyncWaterfallHook[params]
tap
/tapAsync
/tapPromise
method.callAsync(...params)
methodThe plugin handler functions are called with the current value and a callback function with the signature (err: Error, nextValue: any) -> void.
When called nextValue
is the current value for the next handler. The current value for the first handler is init
. After all handlers are applied, callback is called with the last value. If any handler passes a value for err
, the callback is called with this error and no more handlers are called.
This plugin pattern is expected for events like before-resolve
and after-resolve
.
Async Series Bail
AsyncSeriesBailHook[params]
tap
/tapAsync
/tapPromise
method.callAsync(...params)
methodAsync Parallel
AsyncParallelHook[params]
tap
/tapAsync
/tapPromise
method.callAsync(...params)
methodWebpack applies configuration defaults after plugins defaults are applied. This allows plugins to feature their own defaults and provides a way to create configuration preset plugins.
Plugins grant unlimited opportunity to perform customizations within the webpack build system. This allows you to create custom asset types, perform unique build modifications, or even enhance the webpack runtime while using middleware. The following are some features of webpack that become useful while writing plugins.
After a compilation is sealed, all structures within the compilation may be traversed.
class MyPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
// Explore each chunk (build output):
compilation.chunks.forEach((chunk) => {
// Explore each module within the chunk (built inputs):
chunk.getModules().forEach((module) => {
// Explore each source file path that was included into the module:
module.buildInfo &&
module.buildInfo.fileDependencies &&
module.buildInfo.fileDependencies.forEach((filepath) => {
// we've learned a lot about the source structure now...
});
});
// Explore each asset filename generated by the chunk:
chunk.files.forEach((filename) => {
// Get the asset source for each file generated by the chunk:
var source = compilation.assets[filename].source();
});
});
callback();
});
}
}
module.exports = MyPlugin;
compilation.modules
: A set of modules (built inputs) in the compilation. Each module manages the build of a raw file from your source library.module.fileDependencies
: An array of source file paths included into a module. This includes the source JavaScript file itself (ex: index.js
), and all dependency asset files (stylesheets, images, etc) that it has required. Reviewing dependencies is useful for seeing what source files belong to a module.compilation.chunks
: A set of chunks (build outputs) in the compilation. Each chunk manages the composition of a final rendered assets.chunk.getModules()
: An array of modules that are included into a chunk. By extension, you may look through each module's dependencies to see what raw source files fed into a chunk.chunk.files
: A Set of output filenames generated by the chunk. You may access these asset sources from the compilation.assets
table.While running webpack middleware, each compilation includes a fileDependencies
Set
(what files are being watched) and a fileTimestamps
Map
that maps watched file paths to a timestamp. These are extremely useful for detecting what files have changed within the compilation:
class MyPlugin {
constructor() {
this.startTime = Date.now();
this.prevTimestamps = new Map();
}
apply(compiler) {
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
const changedFiles = Array.from(compilation.fileTimestamps.keys()).filter(
(watchfile) => {
return (
(this.prevTimestamps.get(watchfile) || this.startTime) <
(compilation.fileTimestamps.get(watchfile) || Infinity)
);
}
);
this.prevTimestamps = compilation.fileTimestamps;
callback();
});
}
}
module.exports = MyPlugin;
You may also feed new file paths into the watch graph to receive compilation triggers when those files change. Add valid file paths into the compilation.fileDependencies
Set
to add them to the watched files.
Similar to the watch graph, you can monitor changed chunks (or modules, for that matter) within a compilation by tracking their hashes.
class MyPlugin {
constructor() {
this.chunkVersions = {};
}
apply(compiler) {
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
var changedChunks = compilation.chunks.filter((chunk) => {
var oldVersion = this.chunkVersions[chunk.name];
this.chunkVersions[chunk.name] = chunk.hash;
return chunk.hash !== oldVersion;
});
callback();
});
}
}
module.exports = MyPlugin;
The release process for deploying webpack is actually quite painless. Read through the following steps, so you have a clear understanding of how it's done.
When merging pull requests into the main
branch, select the Create Merge Commit option.
npm version patch && git push --follow-tags && npm publish
npm version minor && git push --follow-tags && npm publish
npm version major && git push --follow-tags && npm publish
This will increment the package version, commits the changes, cuts a local tag, push to github & publish the npm package.
After that go to the github releases page and write a Changelog for the new tag.
When contributing to the core repo, writing a loader/plugin, or even working on a complex project, debugging tools can be central to your workflow. Whether the problem is slow performance on a large project or an unhelpful traceback, the following utilities can make figuring it out less painful.
stats
data made available through Node and the CLI.Whether you want to sift through this data manually or use a tool to process it, the stats
data can be extremely useful when debugging build issues. We won't go in depth here as there's an entire page dedicated to its contents, but know that you can use it to find the following information:
On top of that, the official analyze tool and various others will accept this data and visualize it in various ways.
While console
statements may work well in straightforward scenarios, sometimes a more robust solution is needed. As most front-end developers already know, Chrome DevTools are a life saver when debugging web applications, but they don’t have to stop there. As of Node v6.3.0+, developers can use the built-in --inspect
flag to debug a node program in DevTools.
Let's start by invoking webpack with the node --inspect
.
Note that we cannot run npm scripts
, e.g. npm run build
, so we'll have to specify the full node_modules
path:
node --inspect ./node_modules/webpack/bin/webpack.js
Which should output something like:
Debugger listening on ws://127.0.0.1:9229/c624201a-250f-416e-a018-300bbec7be2c
For help see https://nodejs.org/en/docs/inspector
Now jump to chrome://inspect
in the browser and you should see any active scripts you've inspected under the Remote Target header. Click the "inspect" link under each script to open a dedicated debugger or the Open dedicated DevTools for Node link for a session that will connect automatically. You can also check out the NiM extension, a handy Chrome plugin that will automatically open a DevTools tab every time you --inspect
a script.
We recommend using the --inspect-brk
flag which will break on the first statement of the script allowing you to go through the source to set breakpoints and start/stop the build as you please. Also, don't forget that you can still pass arguments to the script. For example, if you have multiple configuration files you could pass --config webpack.prod.js
to specify the configuration you'd like to debug.