Reputation: 911
I have a custom Webpack loader where I'm traversing through the AST of the code using Babel to change the import name of a module. However, it seems like this is affecting the source maps of modules, even when the loader doesn't make any changes to their AST. Why is this happening?
const parser = require('@babel/parser');
const babel = require('@babel/core');
module.exports = function(source, map) {
const removeProxyImports = (source) => {
try {
const filepath = this.resourcePath;
const ast = parser.parse(source, { sourceType: 'module' });
babel.traverse(ast, {
ImportDeclaration(path) {
if (path.node.source && path.node.source.value.includes('ProxyFlow')) {
const val = path.node.source.value.replace('ProxyFlow.', '');
// ... some validation code
path.node.source.value = val;
}
},
});
//TODO: if not modified, don't do babel transformation
const { code } = babel.transformFromAstSync(ast, source);
return code;
} catch (e) {
throw new Error('failed ' + e);
}
};
const code = removeProxyImports(source);
this.callback(null, code, map);
};
I've read that even if no code changes are made, simply parsing and traversing the AST can affect the source map if it's not handled correctly. Regenerating and passing the source map ensures that the mappings between the original source code and the transformed code remain accurate.
I can fix this by also generating the sourcemap while generating the code from ast.
if(!modified){
return { code : source, map};
}
const { code, map: newMap } = babel.transformFromAstSync(ast, source, {
sourceMaps: true,
inputSourceMap: map, // Pass the existing source map
});
return { code , map : newMap}
But why do we even need the fix. Why does even changing the import is corrupting my sourcemap, even though my sourcemap doesn't even have mapping for imports?
Upvotes: 0
Views: 98
Reputation: 911
Since its an AST transformation, babel is not retaining metadata like line breaks, spaces etc... for me it is sometimes adding/deleting lines/spaces which was messing up with my sourcemaps. So its always crucial to regenerate the sourcemaps in order to make sure its in sync with the newly generated code even though its not transformed in any way.
Upvotes: 0