使用节点 js 在特定位置的文件中添加内容(如 Angular CLI 修改 app.module 文件)

Adding content in file in specific place with node js (Like Angular Cli Modify app.module file)

我认为 node js 不仅适用于 Web 应用程序,例如我可以使用 node (cli) 创建控制台应用程序。 我已经对如何制作一个创建文件和修改现有文件的 cli 应用程序感兴趣,例如 angular cli 和一个命令“ng generate component”它的 :-

1- 创建一组文件

2-修改app.module文件

a. add import statement for generated component

b. add generated component in declarations array

经过大量搜索,我发现第一步可以通过节点文件系统模块以某种方式处理。

但我不知道他们如何通过在正确的位置添加一些语法来修改“app.module”文件,例如在所有存在的导入语句之后添加新的导入语句,还在声明数组中添加组件名称作为最后一项 如果可能的话,我真的很感激任何代码示例的帮助,并在此先感谢

经过一些搜索,我找到了这个答案:

There a couple of ways of editing a file, the most reliable is perhaps the most complex one which can be done by parsing the file (Generating an abstract syntax tree) update the new ast and pass it to a code generator which will output the new string (code) of the modified ast. Another option is to use regular expressions to know where add to certain statements. For example there would be a regex to match import statements to lines, you will map the lines of the file to this regex where you'll get an array of booleans denoting whether the line is an import stmt. Or not, once the import stmts are finished you can insert a new line with the new import statement in the original lines array. A third option is to regenerate the file all at once everytime, but this means that you'll have to a ctx of the project (ctx = object contains some details.

作为参考,我发现 AST(抽象语法树)是更可靠的方式,而且它并不难,这些链接帮助我以简单的方式了解什么是 AST 以及如何处理它

1- 什么是 AST 以及如何理解和使用它 https://www.youtube.com/watch?v=tM_S-pa4xDk

2- 这是一篇关于“编写代码以使用 jscodeshift 重写您的代码”的精彩文章 https://www.toptal.com/javascript/write-code-to-rewrite-your-code https://www.youtube.com/watch?v=tM_S-pa4xDk