dart check if is building
Asked Answered
B

1

3

I would like to skip some specific code on pub build.

example:

Log.print('something ${StackTrace.current}');

I would like that the code above was not transpilled to JS in production.

Batish answered 27/2, 2017 at 13:49 Comment(0)
K
3

Asserts are only executed in checked mode and won't be included by pub build in production mode by default:

assert(() {
  Log.print('something ${StackTrace.current}');
  return true;
})

DartPad example doesn't print it because it builds in production mode.

You can also pass "environment" (not mix up with OS environment variables) to pub build and read it in code

transformers: # or dev_transformers
- $dart2js:
  environment: { PROD: "true" }
const prod = String.fromEnvironment('PROD')
print('PROD: $prod');
// prints 'PROD: null' in Dartium
// prints 'PROD: true' in Chrome

See also https://mcmap.net/q/1987512/-dart-how-to-use-different-settings-in-debug-and-production-mode

Keratinize answered 27/2, 2017 at 13:52 Comment(3)
For curiosity: If I put the entire Log.print function within an assert, the calls for the function will also be removed by the tree shaking?Batish
Yes. It should also be removed if you leave it outside of assert(...) and only call it from inside. If it's not used from anywhere, tree-shaking should remove it, also if it's used from code that doesn't make it into the build output like the one from within assert(...).Caudill
See Compile-time dead code elimination with dart2js and bool.fromEnvironment doc for more infosHostetter

© 2022 - 2024 — McMap. All rights reserved.