Dart 2 conditional imports update
With Dart 2 being released for a while, it was time to check if conditional imports still work the same as in Dart 1. You can check what it looked like in this article: https://medium.com/@dvargahali/dart-vm-tests-with-dart-html-yes-you-can-c15439e49cc1
The Dart 1 way
I would go around and write imports/exports like so:
import "something.dart" if (condition) "other.dart";
And run the code with a simple -D
command line argument to the Dart VM.
dart -Dcondition=true myapp.dart
The Dart 2 way
As per this issue https://github.com/dart-lang/sdk/issues/34262 , conditional imports were an undocumented feature for a reason. They kept parts of it alive, while removing other functionality.
What you can still do is use the feature based on conditions defined by Dart VM. These are constrained to checking the presence of libraries.
import "something.dart" if (dart.library.io) "other.dart"
You can check this example of dart-sass library for a production use-case.
What you no longer can do is use custom conditions. Most of what I wrote in my previous article no longer applies. -D
is no longer taken into consideration. This was confirmed by Dart Team members and support for user defined conditions is unlikely to land in Dart.
Upgrade tips
In my use-cases, most of what I needed was checking the deployment target. Browser or VM. This can still be done by checking if dart.library.io
or dart.library.js
is defined.
My other use-cases could be solved by wrapping the implementation classes into a factory and tie it with some environment variables.