Can Yeoman generators update existing files?

前端 未结 5 1983
旧巷少年郎
旧巷少年郎 2021-01-30 10:57

So just to give you some context, I\'m trying to create a generator that will create some files (based on user input of course) as well as update some existing files in

5条回答
  •  时光取名叫无心
    2021-01-30 11:54

    In combination with @sepans' excellent answer, instead of using regular expressions, one can use some parser.

    From Yeoman documentation:

    Tip: Update existing file's content

    Updating a pre-existing file is not always a simple task. The most reliable way to do so is to parse the file AST and edit it. The main issue with this solution is that editing an AST can be verbose and a bit hard to grasp.

    Some popular AST parsers are:

    • Cheerio for parsing HTML.
    • Esprima for parsing JavaScript - you might be interested in AST-Query which provide a lower level API to edit Esprima syntax tree.
    • For JSON files, you can use the native JSON object methods.

    Parsing a code file with RegEx is perilous path, and before doing so, you should read this CS anthropological answers and grasp the flaws of RegEx parsing. If you do choose to edit existing files using RegEx rather than AST tree, please be careful and provide complete unit tests. - Please please, don't break your users' code.

    More specifically, when using esprima you will most probably require also some generator such as escodegen to generate js back.

    var templatePath = this.destinationPath(...);
    this.fs.copy(templatePath, templatePath, {
      process: function (content) {
        // here use the parser
        return ...
      }
    });
    

    Note that you can use the same path in from, to arguments in order to replace the existing file.

    On the other hand, the downside of such parsers is that in some cases it may alter the original file way too much, and although safe, this is more intrusive.

提交回复
热议问题