Search code examples
angularbuilddartdevelopment-environment

Build-time value injection in Dart


I'm relatively new to Dart, but I'm trying to use Dart 2 and Angular 5 to build a fairly simple UI to communicate with an API. Two objectives I have set for myself are that

  1. The API be hosted on App Engine and the UI on Firebase Hosting, as separate modules;
  2. The two modules be easily usable on my local dev machine without having to modify code before a deploy.

To achieve this, I was thinking of using something like Maven's property injection or Gradle's BuildConfigField to inject the API host during build, setting http://localhost:8080 while in development and https://api.example.com in production, but I couldn't find anything to this end in Dart/build_runner.

Is this something that's considered a good practice in Dart-Angular? If so, how can I achieve it? If not, what would be good practice?


Solution

  • Sounds like you are looking for

    https://github.com/dart-lang/webdev/issues/73
    if you use webdev or

    https://github.com/dart-lang/build/issues/1053 if you use pub run build_runner --config=dev ...

    You can configure variables in build.dev.yaml with different values for a different config

    From https://github.com/dart-lang/build/issues/1053#issuecomment-368345014

    targets:
      runny:
        sources:
          exclude: ["lib/builder.dart"]
        builders:
          sass_builder|sass_builder:
            enabled: False
          angular_components|scss_builder:
            enabled: True
          build_web_compilers|entrypoint:
            generate_for:
            - web/main.dart
            options:
              compiler: dartdevc
              dart2js_args:
              - --define env=dev
    

    You can the read the value using

    const currentEnv = String.fromEnvironment('env');
    

    https://docs.flutter.io/flutter/dart-core/String/String.fromEnvironment.html