benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
5.01k stars 350 forks source link

Recast is breaking template code #611

Open X-Ryl669 opened 5 years ago

X-Ryl669 commented 5 years ago

Let's say you have this:

var el = `<div id="it_${i}">`;

If you modify the TemplateElement's node.value.raw (containing <div id="it_) to, let's say (<div id="i_), then recast will print:

var el = `<div id="i_ ${i}">`;

which is breaking the templated text (notice the extra space). I've debugged this and found out the issue is in patcher.js:199 where needsTrailingSpace is set to true with a Line containing (<div id="i_"). nts is true because the last char of my modification is _ and the next unmodified node is starting with $.

I think this should not be applied for TemplateElement node, since inside a template, you must not change the content

X-Ryl669 commented 5 years ago

Indeed, changing patcher.js:199 to read:

   var nls = oldNode.type !== 'TemplateElement' && needsLeadingSpace(lines, oldNode.loc, newLines);
   var nts = oldNode.type !== 'TemplateElement' && needsTrailingSpace(lines, oldNode.loc, newLines);

fixes the issue.