JavascriptParser Hooks

The parser instance, found in the compiler, is used to parse each module being processed by webpack. The parser is yet another webpack class that extends tapable and provides a variety of tapable hooks that can be used by plugin authors to customize the parsing process.

The parser is found within NormalModuleFactory and therefore takes little more work to access:

compiler.hooks.normalModuleFactory.tap("MyPlugin", (factory) => {
  factory.hooks.parser
    .for("javascript/auto")
    .tap("MyPlugin", (parser, options) => {
      // The `parser` provides many hooks, which are explained in detail below.
      // Here is a practical example using the `call` hook to detect and warn
      // about a deprecated API function when a developer calls it
      // (e.g., `myCustomApiFunction()`):
      parser.hooks.call
        .for("myCustomApiFunction")
        .tap("MyPlugin", (expression) => {
          console.warn(
            `Warning: 'myCustomApiFunction' is deprecated. Found call at line ${expression.loc.start.line}.`,
          );
        });
    });
});

As with the compiler, tapAsync and tapPromise may also be available depending on the type of hook.

Hooks

The following lifecycle hooks are exposed by the parser and can be accessed as such:

evaluateTypeof

SyncBailHook

Triggered when evaluating an expression consisting in a typeof of a free variable

  • Hook Parameters: identifier
  • Callback Parameters: expression
parser.hooks.evaluateTypeof.for("myIdentifier").tap(
  "MyPlugin",
  (expression) =>
    /* ... */
    expressionResult,
);

This will trigger the evaluateTypeof hook:

const a = typeof myIdentifier;

This won't trigger:

const myIdentifier = 0;
const b = typeof myIdentifier;

evaluate

SyncBailHook

Called when evaluating an expression.

  • Hook parameters: expressionType
  • Callback parameters: expression

For example:

index.js

const a = new MyClass();

MyPlugin.js

parser.hooks.evaluate.for("NewExpression").tap(
  "MyPlugin",
  (expression) =>
    /* ... */
    expressionResult,
);

Where the expressions types are:

  • 'ArrowFunctionExpression'
  • 'AssignmentExpression'
  • 'AwaitExpression'
  • 'BinaryExpression'
  • 'CallExpression'
  • 'ClassExpression'
  • 'ConditionalExpression'
  • 'FunctionExpression'
  • 'Identifier'
  • 'LogicalExpression'
  • 'MemberExpression'
  • 'NewExpression'
  • 'ObjectExpression'
  • 'SequenceExpression'
  • 'SpreadElement'
  • 'TaggedTemplateExpression'
  • 'TemplateLiteral'
  • 'ThisExpression'
  • 'UnaryExpression'
  • 'UpdateExpression'

evaluateIdentifier

SyncBailHook

Called when evaluating an identifier that is a free variable.

  • Hook Parameters: identifier
  • Callback Parameters: expression

evaluateDefinedIdentifier

SyncBailHook

Called when evaluating an identifier that is a defined variable.

  • Hook Parameters: identifier
  • Callback Parameters: expression

evaluateCallExpressionMember

SyncBailHook

Called when evaluating a call to a member function of a successfully evaluated expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression param

This expression will trigger the hook:

index.js

const a = expression.myFunc();

MyPlugin.js

parser.hooks.evaluateCallExpressionMember.for("myFunc").tap(
  "MyPlugin",
  (expression, param) =>
    /* ... */
    expressionResult,
);

statement

SyncBailHook

General purpose hook that is called for every parsed statement in a code fragment.

  • Callback Parameters: statement
parser.hooks.statement.tap("MyPlugin", (statement) => {
  /* ... */
});

Where the statement.type could be:

  • 'BlockStatement'
  • 'VariableDeclaration'
  • 'FunctionDeclaration'
  • 'ReturnStatement'
  • 'ClassDeclaration'
  • 'ExpressionStatement'
  • 'ImportDeclaration'
  • 'ExportAllDeclaration'
  • 'ExportDefaultDeclaration'
  • 'ExportNamedDeclaration'
  • 'IfStatement'
  • 'SwitchStatement'
  • 'ForInStatement'
  • 'ForOfStatement'
  • 'ForStatement'
  • 'WhileStatement'
  • 'DoWhileStatement'
  • 'ThrowStatement'
  • 'TryStatement'
  • 'LabeledStatement'
  • 'WithStatement'

preStatement

SyncBailHook

Called for every statement during the pre-walk, before any statement of the block is walked. This is where hoisted declarations are seen. Returning true tells the parser the statement was handled and stops the default pre-walk for it.

  • Callback Parameters: statement

blockPreStatement

SyncBailHook

Same as preStatement, but for the block pre-walk, which only visits declarations scoped to the current block.

  • Callback Parameters: statement

unusedStatement

SyncBailHook

Called for each statement that follows a terminating statement in the same block and is therefore unreachable. Returning true skips walking it.

  • Callback Parameters: statement

terminate

SyncBailHook

Called for a return or throw statement outside the top-level scope. Returning true marks the scope as terminated, so the parser treats the statements after it as unreachable.

  • Callback Parameters: statement

statementIf

SyncBailHook

Called when parsing an if statement. Same as the statement hook, but triggered only when statement.type == 'IfStatement'.

  • Callback Parameters: statement

label

SyncBailHook

Called when parsing statements with a label. Those statements have statement.type === 'LabeledStatement'.

  • Hook Parameters: labelName
  • Callback Parameters: statement

import

SyncBailHook

Called for every import statement in a code fragment. The source parameter contains the name of the imported file.

  • Callback Parameters: statement source

The following import statement will trigger the hook once:

index.js

import _ from "lodash";

MyPlugin.js

parser.hooks.import.tap("MyPlugin", (statement, source) => {
  // source == 'lodash'
});

importSpecifier

SyncBailHook

Called for every specifier of every import statement.

  • Callback Parameters: statement source exportName identifierName

The following import statement will trigger the hook twice:

index.js

import _, { has } from "lodash";

MyPlugin.js

parser.hooks.importSpecifier.tap(
  "MyPlugin",
  (statement, source, exportName, identifierName) => {
    /* First call
    source == 'lodash'
    exportName == 'default'
    identifierName == '_'
  */
    /* Second call
    source == 'lodash'
    exportName == 'has'
    identifierName == 'has'
  */
  },
);

export

SyncBailHook

Called for every export statement in a code fragment.

  • Callback Parameters: statement

exportImport

SyncBailHook

Called for every export-import statement eg: export * from 'otherModule';.

  • Callback Parameters: statement source

exportDeclaration

SyncBailHook

Called for every export statement exporting a declaration.

  • Callback Parameters: statement declaration

Those exports will trigger this hook:

export const myVar = "hello"; // also var, let
export function FunctionName() {}
export class ClassName {}

exportExpression

SyncBailHook

Called for every export statement exporting an expression e.g.export default expression;.

  • Callback Parameters: statement declaration

exportSpecifier

SyncBailHook

Called for every specifier of every export statement.

  • Callback Parameters: statement identifierName exportName index

exportImportSpecifier

SyncBailHook

Called for every specifier of every export-import statement.

  • Callback Parameters: statement source identifierName exportName index

varDeclaration

HookMap<SyncBailHook>

Called when parsing a variable declaration, once for each declared identifier. The callback receives the Identifier node.

  • Hook Parameters: identifier
  • Callback Parameters: identifier
const a = 1;

parser.hooks.varDeclaration.for("a").tap("MyPlugin", (identifier) => {
  // identifier is the `Identifier` node of a
});

preDeclarator

SyncBailHook

Called for each declarator of a variable declaration during the pre-walk, before the declaration itself is walked.

  • Callback Parameters: declarator declaration

declarator

SyncBailHook

Called for each declarator of a variable declaration while walking it. Returning true stops the parser from walking that declarator itself.

  • Callback Parameters: declarator statement

varDeclarationLet

HookMap<SyncBailHook>

Called when parsing a variable declaration defined using let

  • Hook Parameters: identifier
  • Callback Parameters: identifier

varDeclarationConst

HookMap<SyncBailHook>

Called when parsing a variable declaration defined using const

  • Hook Parameters: identifier
  • Callback Parameters: identifier

varDeclarationVar

HookMap<SyncBailHook>

Called when parsing a variable declaration defined using var

  • Hook Parameters: identifier
  • Callback Parameters: identifier

canRename

SyncBailHook

Triggered before renaming an identifier to determine if the renaming is allowed. This is usually used together with the rename hook.

  • Hook Parameters: identifier
  • Callback Parameters: expression
const a = b;

parser.hooks.canRename.for("b").tap(
  "MyPlugin",
  (expression) =>
    // returning true allows renaming
    true,
);

rename

SyncBailHook

Triggered when renaming to get the new identifier. This hook will be called only if canRename returns true.

  • Hook Parameters: identifier
  • Callback Parameters: expression
const a = b;

parser.hooks.rename.for("b").tap("MyPlugin", (expression) => {});

assign

SyncBailHook

Called when parsing an AssignmentExpression, after the assigned expression has been walked and before the target is walked. Returning true prevents the target from being walked.

  • Hook Parameters: identifier
  • Callback Parameters: expression
a += b;

parser.hooks.assign.for("a").tap("MyPlugin", (expression) => {
  // this is called after b has been walked, before a is walked
});

typeof

SyncBailHook

Triggered when parsing the typeof of an identifier

  • Hook Parameters: identifier
  • Callback Parameters: expression

call

SyncBailHook

Called when parsing a function call.

  • Hook Parameters: identifier
  • Callback Parameters: expression
eval(/* something */);

parser.hooks.call.for("eval").tap("MyPlugin", (expression) => {});

callMemberChain

SyncBailHook

Triggered when parsing a call to a member function of an object.

  • Hook Parameters: objectIdentifier
  • Callback Parameters: expression, properties
myObj.anyFunc();

parser.hooks.callMemberChain
  .for("myObj")
  .tap("MyPlugin", (expression, properties) => {});

new

SyncBailHook

Invoked when parsing a new expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
new MyClass();

parser.hooks.new.for("MyClass").tap("MyPlugin", (expression) => {});

expression

SyncBailHook

Called when parsing an expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
const a = this;

parser.hooks.expression.for("this").tap("MyPlugin", (expression) => {});

expressionConditionalOperator

SyncBailHook

Called when parsing a ConditionalExpression e.g. condition ? a : b

  • Callback Parameters: expression

expressionLogicalOperator

SyncBailHook

Called when parsing a LogicalExpression e.g. a && b or a || b. Returning a value stops the parser from walking the operands itself, which is how a plugin can skip a branch it evaluated as dead.

  • Callback Parameters: expression

binaryExpression

SyncBailHook

Called when parsing a BinaryExpression e.g. a === b. Returning a value stops the default walk of both operands.

  • Callback Parameters: expression

optionalChaining

SyncBailHook

Called when parsing a ChainExpression, i.e. an expression using optional chaining such as a?.b or a?.().

  • Callback Parameters: expression

importCall

SyncBailHook

Called when parsing a dynamic import(). Returning true marks the call as handled, so webpack creates no dependency of its own for it.

  • Callback Parameters: expression callExpression

callExpression is only given when the import() is immediately called, e.g. import("./m").then(...).

topLevelAwait

SyncBailHook

Called when a top-level await is parsed, which is what turns the module into an async module.

  • Callback Parameters: expression

classExtendsExpression

SyncBailHook

Called with the expression a class extends, e.g. Base in class A extends Base {}.

  • Callback Parameters: expression classDefinition

classBodyElement

SyncBailHook

Called for each element of a class body — a method, a property definition or a static block. Returning true stops the parser from walking that element.

  • Callback Parameters: element classDefinition

classBodyValue

SyncBailHook

Called for the value of a class body element, i.e. a field initializer or a method's function expression. Returning true stops the parser from walking it.

  • Callback Parameters: expression element classDefinition

collectDestructuringAssignmentProperties

SyncBailHook

Called for a destructuring assignment so the properties it reads can be collected, which is what lets webpack treat a destructured import as a reference to only those exports.

  • Callback Parameters: expression

collectGuards

SyncBailHook

Called with the test of a conditional expression to collect the guards it implies, so the parser can narrow what the branches may evaluate to.

  • Callback Parameters: expression

program

SyncBailHook

Get access to the abstract syntax tree (AST) of a code fragment

  • Parameters: ast comments
Edit this page·

7 Contributors

byzykDeTeammisterdevEugeneHlushkochenxsansnitin315moshams272