babel-generator编写AST

时间:2017-12-24 23:00:34

标签: abstract-syntax-tree babel

在编写从另一个文件中注入代码的插件时...另一个文件被转换并注入到原始文件的AST中

astB = babel.transformFileSync(templatename, { plugins:plugins, code:false});

之后,请致电:

generate(ast, { sourceMaps: true, retainLines: false, quotes:"'"}, codes);

导致错误

Error: Invalid mapping: {"generated":{"line":30,"column":0},"original":{"line":1,"column":0}}
at SourceMapGenerator_validateMapping [as _validateMapping] (node_modules\babel-generator\node_modules\source-map\lib\source-map-generator.js:289:13)
at SourceMapGenerator_addMapping [as addMapping] (node_modules\babel-generator\node_modules\source-map\lib\source-map-generator.js:101:12)
at Array.forEach (<anonymous>)
at SourceMap.get (node_modules\babel-generator\lib\source-map.js:49:25)
at Object.get [as map] (node_modules\babel-generator\lib\buffer.js:53:33)
at writeAst (test2.js:59:24)
at Object.<anonymous> (test2.js:55:1)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)

1 个答案:

答案 0 :(得分:0)

从错误中不是很明显,但问题是注入的代码称为解析器作为转换的一部分,并且没有提供文件名。

使用转换更改行修复了问题

添加parserOpts:{sourceFilename: templatename}代码变为:

astB = babel.transformFileSync(templatename, {parserOpts:{sourceFilename: templatename}, plugins:plugins, code:false});