admin管理员组

文章数量:1287630

I have a FunnelWeb file whose @{...@} code blocks are tangled into a Javascript program. I want to use prettier to format these code blocks while leaving the non-code FunnelWeb source unchanged.

Here is my approach, my question is: are there better alternatives?

I use a Node.js program that processes the file line by line. Unless it is in "code block" state, it simply copies each line to the output. But:

  • If a line starts with a code block definition @$@<...@>@{, it outputs that line, creates a new code buffer and switches to "code block" state.
  • If it is in "code block" state, it adds the line to the code buffer.
  • If a line starts with @}, it leaves the "code block" state, formats the code buffer with prettier and outputs the resulting lines, followed by the current line.

The problem is that the contents of the @{...@} code block in the code buffer typically do not contain a Javascript program considered error-free by prettier. This is because FunnelWeb works by pasting code blocks together and into other code blocks without any regard to the programming language that they contain. In particular

  • a code block may contain @<...@> references to other code blocks
  • a code block often contains one method of a class and looks like
    method(args) {...}
    
    and prettier rejects this in the absence of the surrounding
    class ClassName {...}
    

To circumvent these two problems, my Node.js program

  • wraps @<...@> in comment syntax like /*@<...@>*/ before prettier formatting and unwraps them afterwards
  • converts an unindented method(args) { into function /*m*/ method(args) { before prettier formatting and converts it back afterwards
  • converts an unindented static method(args) { into function /*s*/ method(args) { before prettier formatting and converts it back afterwards.

The after-prettier processing thus performs

code = code
  .replaceAll("function /*s*/", "static")
  .replaceAll("function /*m*/ ", "")
  .replace(/\/\*|\*\//g, "");

And if a code block still cannot be formatted by prettier, the unformatted code is output.

With this approach my code blocks that cannot be formatted are mostly one-liners like

@$@<Exports@>+=@{
ClassName,
@}

Again my question: Has anyone else tried this and found a better approach?

本文标签: Use prettier to format Javascript code blocks in a FunnelWeb fileStack Overflow