Search code examples
javascriptwebpacksource-mapswebpack-plugin

Webpack plugin API: getting source maps for a module during parsing


I'm writing a code analyzer. My analyzer uses Webpack's JavaScriptParser hooks. I need to output an error message, but the line number from node.loc is off because a loader has transformed the source code. So I want to feed the error message through a source map before logging it.

class FooPlugin {
    apply(compiler) {
        compiler.hooks.normalModuleFactory.tap("FooPlugin", factory => {
            factory.hooks.parser
                .for('javascript/auto')
                .tap("FooPlugin", parser => {
                    parser.hooks.call.for("foo").tap("FooPlugin", expr => {
                        const map = getSourceMapSomehow();  /* ??? */
                        const originalLine = map.originalPositionFor(expr.loc.start).line;
                        console.log("foo() call found at line " + originalLine);
                    });
                });
        });
    }
}

I can't figure out how to fill in getSourceMapSomehow() in the example above. How can I get the source map for the current module inside a JavaScriptParser hook?


Solution

  • I figured it out by reading the Webpack source code. The function I needed was module.originalSource().

    const map = new SourceMapConsumer(parser.state.module.originalSource().map());
    const originalLine = map.originalPositionFor(expr.loc.start).line;
    console.log("foo() call found at line " + originalLine);