如何在另一个代码生成器的顶部运行代码生成器? [英] How to run a code-generator on the top of another code-generator?

查看:62
本文介绍了如何在另一个代码生成器的顶部运行代码生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 source_gen 堆栈来生成代码生成器,如何使生成器生成将是另一个生成器的输入的代码(更具体地说是 json_serializable )?

Using the source_gen stack to make a code generator, how can I make a generator that generates code that would be the input of another generator (more specifically json_serializable)?

例如,考虑:

class Example extends Generator {
  @override
  String generate(LibraryReader library, BuildStep buildStep) {
    return '''
@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _PersonFromJson(json);
  Map<String, dynamic> toJson() => _PersonToJson(this);
}
''';
  }
}

这是代码生成器的示例,该代码生成器输出代码,然后需要将其发送到 json_serializable

This is an example of a code-generator that output code which then needs to be sent to json_serializable

我该怎么做才能在此处正确生成 json_serializable ?

What can I do so that json_serializable correctly generates here?

推荐答案

查看build.yaml配置文件文档以获取更多信息,但是我认为您应该使用

Check the build.yaml config file documentation for more info, but I think you should use the applies_builders param that allows to execute another build after the defined one.

该示例显示了一个生成器,该生成器生成.tar.gz文件,然后执行另一个将.tar.gz文件作为输入的构建

The example shows a builder that generates .tar.gz files and then executes another build that takes the .tar.gz files as input

builders:
  # The regular builder config, creates .tar.gz files.
  regular_builder:
    import: "package:my_package/builder.dart"
    builder_factories: ["myBuilder"]
    build_extensions: {".dart": [".tar.gz"]}
    auto_apply: dependents
    apply_builders: [":archive_extract_builder"]
post_process_builders:
  # The post process builder config, extracts .tar.gz files.
  extract_archive_builder:
    import: "package:my_package/extract_archive_builder.dart"
    builder_factory: "myExtractArchiveBuilder"
    input_extensions: [".tar.gz"]

因此,对于 source_gen ,您应该为自己的构建实现

so with source_gen you should implement for your build

applies_builders: ["source_gen|combining_builder", "json_serializable"]

并配置其他构建器

json_serializable:
    import: "package:json_serializable/builder.dart"
    builder_factories: ["jsonSerializable"]
    build_extensions: {".dart": ["json_serializable.g.part"]}
    auto_apply: dependents
    build_to: cache
    applies_builders: ["source_gen|combining_builder"]

这篇关于如何在另一个代码生成器的顶部运行代码生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆