asyncLiz / parse-literals

Parse template literals from code
MIT License
9 stars 2 forks source link

get script parts as well #1

Closed roeycohen closed 5 years ago

roeycohen commented 5 years ago

Hi,

it would be nice if the library will also return the locations of scripts. this way you could modify them as well, for example, add escaping.

10x!

roeycohen commented 5 years ago

can also be nice to return tag locations in case someone would like to remove or change it.

asyncLiz commented 5 years ago

I'm not sure if it makes sense to return the text of the substitution values. Developers would then have to parse two potential part types, either a string part or a substitution part.

That seems like an unnecessary complication when it's pretty trivial to get the substitution text and tag location with what is provided.

const code = `
  render() {
    return html\`
      <h1>\${"Hello World"}</h1>
    \`;
  }
`;

const templates = parseLiterals(code);
const template = templates[0];
if (template.tag) {
  const tagEnd = template.parts[0].start; // exclusive index
  const tagStart = tagEnd - 1 - template.tag.length; // inclusive index
  console.log(code.slice(tagStart, tagEnd)); // html
}

for (let i = 0; i < template.parts.length; i++) {
  const part = template.parts[i];
  const next = template.parts[i + 1];
  if (next) {
    // Substitution is between two parts only
    const subStart = part.end + 2; // add 2 for "${"
    const subEnd = next.start - 1; // sub 1 for "}"
    console.log(code.slice(subStart, subEnd)); // "Hello World"
  }
}
asyncLiz commented 5 years ago

@roeycohen let me know if the above solution works for you

roeycohen commented 5 years ago

seems legit 👍 10x!