Module Object

Every file webpack builds becomes a Module in the compilation. Plugins meet them everywhere — iterating compilation.modules, on the succeedModule hook, behind moduleGraph.getIssuer(module) — and a loader can reach its own through the loader context.

Module is a base class. What a build actually holds is one of its subclasses, and which one depends on where the module came from:

ClassComes from
NormalModulea resolved file processed by loaders — the usual case
RawModulesource webpack generated itself, with no file behind it
ExternalModulea request matched by externals
ContextModulea context, i.e. a require of an expression
ConcatenatedModuleseveral modules merged by optimization.concatenateModules
DllModulea module delivered by DllReferencePlugin

Properties on every module

type

string

The module type, e.g. 'javascript/auto', 'javascript/esm', 'json', 'css/auto', 'asset/resource', 'webassembly/async'. A plugin can add its own, so match a prefix rather than a fixed list when you mean "any JavaScript".

layer

string | null

The layer the module was built in, or null.

context

string | null

The absolute path of the directory the module's requests are resolved against.

buildMeta

object

What the parser worked out about the module, filled during the build. The fields a plugin normally reads:

FieldMeaning
exportsTypehow the module's exports are consumed: 'namespace', 'default', 'flagged', 'dynamic', or undefined
defaultObjecthow a default import of a CommonJS module is built: false, 'redirect', 'redirect-warn'
strictHarmonyModulethe module is ESM and must be treated strictly
asyncthe module is asynchronous (top-level await)
sideEffectFreethe module was determined to have no side effects

buildInfo

object

What the build itself produced — dependencies to watch, assets emitted from the module, and whether the result may be cached:

FieldMeaning
cacheablefalse when a loader called this.cacheable(false)
fileDependencies, contextDependencies, missingDependenciespaths watched for changes, as collected from the loader context
buildDependenciespaths whose change invalidates the persistent cache, from this.addBuildDependency()
assets, assetsInfoassets the module emitted through this.emitFile()
strict, exportsArgument, moduleArgumentset by the parser; they shape the code the generator emits
hashthe hash of the build result

buildInfo is serialized with the module, so it is also where a loader leaves data for a plugin to pick up: it is still there on a build restored from the persistent cache, where the loader itself never runs again. Store plain, serializable values only, under a property named after your plugin.

dependencies

Dependency[]

What the module requires. presentationalDependencies holds the ones that only affect code generation, and blocks (AsyncDependenciesBlock[]) the ones behind an import(). To find the module a dependency points at, ask the graph: moduleGraph.getModule(dependency).

factoryMeta

object

Set by the module factory before the build, e.g. sideEffectFree derived from the package's sideEffects field.

Methods on every module

identifier

function () => string

A string that identifies the module uniquely in the compilation — the request with all loaders and their options. It is the key compilation.findModule looks up.

readableIdentifier

function (requestShortener) => string

The same identity in the shortened form stats and warnings print. Take the shortener from compilation.requestShortener.

originalSource

function () => Source | null

The module's source before code generation, or null for a module that has none.

getSourceTypes

function () => Set<string>

Which kinds of code the module can generate, e.g. 'javascript', 'css', 'asset'. Ask the module instead of deriving it from type.

size

function (type) => number

The size of the module's source of that type, in bytes.

nameForCondition

function () => string | null

The path rule conditions are matched against — the resource without its query and fragment. null when the module has no file behind it.

addError / addWarning / getErrors / getWarnings

function

Diagnostics attached to the module. One added here is reported against the module and survives into the cache, unlike a compilation.errors entry pushed after seal.

Properties of a NormalModule

A NormalModule is a resolved file plus the loaders applied to it, so it carries the parts of the request separately:

PropertyExample for 'babel-loader!./src/app.js?x=1'
requestthe full request with all resolved loaders, '/abs/babel-loader.js!/abs/src/app.js?x=1'
userRequestthe request without automatically added loaders
rawRequestthe request as written in the source, './app.js?x=1'
resourcethe resolved file with query and fragment, '/abs/src/app.js?x=1'
matchResourcethe !=! match resource, if any
resourceResolveDatawhat the resolver returned — descriptionFileData holds the package.json
loaders[{ loader, options, ident, type }] in the order they run
binarytrue for asset and WebAssembly modules, whose source is a Buffer

A loader reaches its own module as this._module. That property is not part of the documented loader context, but loader/plugin pairs rely on it.

class MyPlugin {
  apply(compiler) {
    const { NormalModule } = compiler.webpack;

    compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
      compilation.hooks.succeedModule.tap("MyPlugin", (module) => {
        if (!(module instanceof NormalModule)) return;

        console.log(module.resource, module.getSourceTypes());
      });
    });
  }
}
Edit this page·

1 Contributor

hai-x