Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use webpack/babel to preparse JS template strings?

Let's say for example, I want to create a rot13 template tag. You could use it like this:

 let secret = rot13`This is a secret.`;

Now I could implement this tag in JavaScript, but I want to pre-parse it such that my compiled bundle would actually contain:

 let secret = "Guvf vf n frperg.";

How can I do this? Do I have to create a Babel plugin to hook into their parser? What would that look like?

Now what if I want Webpack to also spit out a file called rotated_strings.txt which contains a list of all these strings that have been transformed? How do I collect them up? i.e., how do I get Babel and Webpack to communicate such that Babel can do the inline transform but somehow notify Webpack to generate this extra file?

like image 490
mpen Avatar asked Oct 18 '22 10:10

mpen


1 Answers

Try out the following.
https://astexplorer.net/#/gist/89a6bdce0165d2661385828d9d85a7e0/4d745f3e8b5bfd25ba919cff567f27055d9e3a75

  • I have built up on what Joe Clay had created in the comments.
  • Right now this console logs all the things it has changed once at the end
  • And in the comments I have written what you can replace it with once you move it to using in your project build env (assuming it to be Node)

PS: I have used the sync APIs in comments to quickly demonstrate it, you should probably switch over to Async APIs

Update: When you write this in Babel plugin, be sure to not set quasi and cooked attrs, but use path.replaceWith(t.stringLiteral(cooked)) instead

like image 58
Aftab Khan Avatar answered Oct 21 '22 02:10

Aftab Khan