buildCloudFunctions function

Future<void> buildCloudFunctions({
  1. OptimizationLevel optimization = OptimizationLevel.O2,
  2. String? output,
  3. String? input,
})

A pre-built function to convert dart code into Functions-compatible JS

A dart file named src/index.dart is compiled to lib/index.js which will be used by the Functions runtime

Implementation

Future<void> buildCloudFunctions({
  OptimizationLevel optimization = OptimizationLevel.O2,
  String? output,
  String? input,
}) async {
  output ??= path.join('lib', 'index.js');
  input ??= path.join('src', 'index.dart');

  final build = await Process.start(
    'dart',
    ['compile', 'js', '-$optimization', '-o', output, input],
    mode: ProcessStartMode.inheritStdio,
  );

  final exitCode = await build.exitCode;
  if (exitCode != 0) {
    throw Exception('Build failed with exit code $exitCode');
  }

  final preamble =
      getPreamble(minified: optimization.index >= OptimizationLevel.O2.index);

  final out = File(output);
  final content = out.readAsStringSync();
  if (content.contains(_beginPreamble)) {
    print('Preamble already present. Skipping preamble injection.');
    return;
  }
  out.writeAsStringSync(
    '$_beginPreamble\n$preamble\n$_endPreamble\n\n$_beginDart\n$content\n$_endDart\n',
  );
}