【问题标题】:Yeoman Generator for Dynamically adding Code用于动态添加代码的 Yeoman 生成器
【发布时间】:2017-04-15 13:27:38
【问题描述】:

我正在尝试为 android 构建一个 Yeoman 项目生成器,它可以从用户那里获取参数并相应地更新已经存在的文件。就像它可以在运行时将一些样板代码放入文件中或在 build.gradle 等中添加依赖项。

例如 我提示用户是否要为 Fabric 添加库依赖项,如果他按是则该库的依赖项

compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') { transitive = true; }

应在 build.gradle 中添加,并应在必要的文件中添加设置此库所需的代码,例如 Application 类的 onCreate 方法应包含

Fabric.with(this, new Crashlytics());

并且 Android.Manifest 应该包含

<meta-data android:name="io.fabric.ApiKey" android:value="your key">

实现这一目标的最佳方法是什么?

谢谢

【问题讨论】:

    标签: android yeoman yeoman-generator


    【解决方案1】:

    理想情况下,您希望从源文件中解析和修改 AST。但是我不知道你是否会找到java代码的AST解析器(对于XML代码,应该很容易)。

    const source = this.fs.read(this.destinationPath('file-to-modify.xml'));
    const manifest = parseXML(source); // any XML parser will work here
    
    // Here you write the code to modify the XML source
    
    this.fs.write(
      this.destinationPath('file-to-modify.xml'),
      serializeXML(manifest) // with whichever XML serializer you want to use
    );
    

    对于 Java 代码,如果没有适当的 AST 解析器,您始终可以依靠正则表达式以类似于 xml 示例的方式在代码字符串中注入新行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2012-08-09
      • 1970-01-01
      • 2010-12-17
      • 2015-04-04
      相关资源
      最近更新 更多