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

Let's say for example I want to create a template tag rot13

. You can 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 so that my compiled package actually contains:

 let secret = "Guvf vf n frperg.";

      

How can i do this? Do I have to create a Babel plugin to connect to their parser? What does it look like?

Now if I want Webpack to also spit out a file named rotated_strings.txt

that contains a list of all those lines that have been converted? How do I collect them? that is, how do I get Babel and Webpack to communicate so that Babel can do the inline transformation, but somehow notifies Webpack to create this extra file?

+3


source to share


1 answer


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

  • I created what Joe Clay created in the comments.
  • At the moment this console logs everything it changed once at the end.
  • And in the comments I wrote that you can replace it as soon as you move it to use in your build env project (let's assume it is Node)


PS: I used the sync APIs in the comments to quickly demonstrate them, you should probably go to Async APIs

Refresh . When you write this in Babel plugin make sure quasi and boiled attrs are not set, but use path.replaceWith(t.stringLiteral(cooked))

instead

+2


source







All Articles