即使没有进行任何更改,Babel 的 AST 遍历如何影响源映射?

问题描述 投票:0回答:1

我有一个自定义的 Webpack 加载器,我使用 Babel 遍历代码的 AST 来更改模块的导入名称。然而,这似乎会影响模块的源映射,即使加载程序没有对其 AST 进行任何更改。为什么会出现这种情况?

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);
};

我读到,即使没有进行任何代码更改,如果处理不当,简单地解析和遍历 AST 也会影响源映射。重新生成并传递源映射可确保原始源代码和转换后的代码之间的映射保持准确。

我可以通过在从 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}

但是为什么我们还需要修复呢?为什么即使更改导入也会损坏我的源映射,即使我的源映射甚至没有导入映射?

javascript webpack babeljs source-maps babel-loader
1个回答
0
投票

由于它是 AST 转换,babel 不会保留像换行符、空格等元数据...对我来说,它有时会添加/删除行/空格,这会弄乱我的源映射。因此,重新生成源映射始终至关重要,以确保其与新生成的代码同步,即使它没有以任何方式进行转换。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.