Koren Minchev
Koren Minchev

Reputation: 81

Dart json serializable fails with custom builder and build.yaml file

I am currently developing my own code generator using the source_gen library in dart as a separate library.
At first this is the build.yaml file I used for it:

builders:
  fields_generator:
    import: "package:sculptor/fields_builder.dart"
    builder_factories: ["fieldBuilder"]
    build_extensions: {".dart": [".json"]}
    auto_apply: dependents
    build_to: source

and everything worked as expected both in the library and in the project using it.

I want to use json_serializable in the generator library and when I try to run the build_runner I encounter one of two problems:

  1. If I add the json_serializable builder to my build.yaml file like this:
builders:
  fields_generator:
    import: "package:sculptor/fields_builder.dart"
    builder_factories: ["fieldBuilder"]
    build_extensions: {".dart": [".json"]}
    auto_apply: dependents
    build_to: source

targets:
  $default:
    builders:
      json_serializable:json_serializable:
        enabled: true

then the build runner throws an error

[WARNING] lib/src/models/mason_params.dart:3:6: Error: Error when reading 'lib/src/models/mason_params.g.dart': No such file or directory
part 'mason_params.g.dart';
     ^
lib/src/models/mason_params.dart:3:6: Error: Can't use 'lib/src/models/mason_params.g.dart' as a part, because it has no 'part of' declaration.
part 'mason_params.g.dart';
     ^
[INFO] Precompiling build script... completed, took 3.1s

[SEVERE] Failed to precompile build script .dart_tool/build/entrypoint/build.dart.
This is likely caused by a misconfigured builder definition.

I tried adding my custom builder to the targets and defining runs_before option to the json_serializable builder but neither had success.

  1. If I change my build.yaml to not contain my custom builder:
targets:
  $default:
    builders:
      json_serializable:json_serializable:
        enabled: true

then build_runner successfully builds the .g.dart files, but the project using my library doesn't build the files my custom generator should generate.

Upvotes: 1

Views: 266

Answers (0)

Related Questions