4

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?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157

1 Answers1

1

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);
Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157