I see two possibilities (haven’t tried any of these myself yet)
- one is to use a transformer (see also Pass custom parameters to a dart application when using pub serve to run it)
or
- Compile-time dead code elimination with dart2js
Recently a feature should have been added that pub build allows adding an environment variables using a command line option (like dart2js’s -d)
log(String msg) {
if (const String.fromEnvironment('DEBUG') != null) {
print('debug: $msg');
}
}
main() {
log('In production, I do not exist');
}
Some links about transformers:
- Can We Build It? Yes, We Can!
- Assets and Transformers
- Day 992: Search and Replace Dart Transformer to Hide from Polymer
- Dart Transformers for Polymer Cleanup
- Pub transformers
- dart2js_dransformer.dart
- Document user-defined transformers
EDIT
I was able to configure dart2js
options in pubspec.yaml like
transformers:
- $dart2js:
commandLineOptions: [-DDEBUG=true]
environment:
DEBUG: "true"
suppressWarnings: true
terse: true
They are validate and pub build
fails if an unknown option is provided or if it’s not the expected format (yaml list
for commandLineOptions, yaml map
form environment)
BUT String.fromEnvironment()
didn’t get a value
According to this issue, this is supported:
Passing in arguments to dart2js during pub build
I filed a bug How to pass options to dart2js from pubspec.yaml
EDIT-2
I tried it and it is working now:
transformers: # or dev_transformers
- $dart2js:
environment: { PROD: "true" }
access it from the code like
String.fromEnvironment()
main() {
print('PROD: ${const String.fromEnvironment('PROD')}');
// works in the browser
// prints 'PROD: null' in Dartium
// prints 'PROD: true' in Chrome
}
see also Configuring the Built-in dart2js Transformer
EDIT-3
Another way is to use assert
to set variables.
assert
is ignored in production.