2

I'm developing an angular app, and it's recommended to use generated code for a lot of things running in production, namely template caches, expression caches, and a static DI injector. There's currently no nice way to switch between different build configurations, so I'm using the pattern recommended here:

In lib/main.dart you can see initializer-prod.dart file being imported, which has initializer-dev.dart counterpart. Switching between those two file will allow you to switch between prod and dev modes. You will need to run the generator script before using the prod mode.

This results in the following import:

//import 'initializer_prod.dart' as init; // Use in prod/test.
import 'initializer_dev.dart' as init; // Use in dev.

As you can see, switching the import is a manual process. Is there a better, more automatic way to achieve this?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
w.brian
  • 16,296
  • 14
  • 69
  • 118

1 Answers1

2

I see two possibilities (haven't tried any of these myself yet)

or

log(String msg) {
  if (const String.fromEnvironment('DEBUG') != null) {
    print('debug: $msg');
  }
}

main() {
  log('In production, I do not exist');
}

Some links about 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.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Regarding option 2) This is not currently support by `pub build` only via direct dart2js invocation. See: http://dartbug.com/15806 – Matt B Jan 24 '14 at 18:03
  • I'm not using pub serve, but applying a transformation prior to dart2dart/dart2js compilation would probably do the trick. Are you aware of any examples where transformations are applied directly instead of via pub serve? – w.brian Jan 24 '14 at 18:35
  • I just tried it and it worked. I published an example project https://github.com/zoechi/build_variables/blob/master/pubspec.yaml#L15 – Günter Zöchbauer Apr 22 '15 at 20:14