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

Time:10-30

I'm writing a code analyser. My analyser uses Webpack's JavaScriptParser hooks. I need to output an error message, but the line number from node.loc is off because the source code has been transformed by a loader. So I wanna 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?

CodePudding user response:

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);
  • Related