Compiling to executables

suggest change

During development you run Dart code with dart run. The Dart VM compiles your code just-in-time (JIT), which gives fast edit-run cycles and hot reload, but it requires the Dart SDK on the machine that runs the program.

To ship a command-line tool or a server, you compile it ahead-of-time (AOT) into native machine code with dart compile. The result starts in milliseconds, uses less memory, and can be copied to a machine that has no Dart SDK installed.

dart compile has several output formats:

Subcommand Output Runs with Portable across OS/CPU
exe self-contained native executable runs directly no
aot-snapshot AOT-compiled code without the runtime dartaotruntime no
jit-snapshot JIT snapshot with pre-warmed code dart run no
kernel portable intermediate form (.dill) dart run yes
js JavaScript browser / Node.js yes
wasm WebAssembly browser yes

This article covers the native formats used for command-line apps and servers: exe, aot-snapshot, jit-snapshot and kernel.

A program to compile

Create a small project with dart create:

dart create -t console greet
cd greet

Replace bin/greet.dart with this:

import 'dart:io';

const version = String.fromEnvironment('APP_VERSION', defaultValue: 'dev');

void main(List<String> args) {
  if (args.contains('--version')) {
    print('greet $version');
    return;
  }
  final name = args.isEmpty ? 'world' : args.join(' ');
  print('Hello, $name!');
  print('Running on ${Platform.operatingSystem} (${Platform.version.split(' ').first})');
  print('Executable: ${Platform.resolvedExecutable}');
}

Run it with the JIT VM:

dart run bin/greet.dart Alice
Hello, Alice!
Running on linux (3.9.4)
Executable: /usr/lib/dart/bin/dart

Platform.resolvedExecutable points at the dart binary, because the VM is what's actually running.

Compiling a self-contained executable

dart compile exe produces a single file that contains your AOT-compiled code plus a small Dart runtime (garbage collector, isolate support, dart:io implementation):

mkdir -p build
dart compile exe bin/greet.dart -o build/greet
Generated: /home/me/greet/build/greet

The output directory must exist: dart compile doesn't create it and fails with PathNotFoundException otherwise.

Run it like any other program:

./build/greet Alice
Hello, Alice!
Running on linux (3.9.4)
Executable: /home/me/greet/build/greet

Now Platform.resolvedExecutable is the compiled file itself.

On Windows, name the output with an .exe extension:

dart compile exe bin\greet.dart -o build\greet.exe

Always pass -o. Without it, the output is written next to the source file as bin/greet.exe, on every OS, including Linux and macOS.

The executable is a few megabytes for a hello-world program. Only code that is reachable from main is included: the AOT compiler does tree shaking, so unused parts of packages you import are left out.

Compared to JIT

You can measure the difference in startup time:

time dart run bin/greet.dart
time ./build/greet

On a typical machine dart run takes a few hundred milliseconds (it has to start the VM, load the sources and compile them), while the compiled executable finishes in around 10-20 ms. For long-running servers the difference in peak performance is smaller: JIT can sometimes beat AOT on hot loops because it optimizes based on observed types, while AOT gives predictable performance from the first request.

Passing compile-time values with -D

-D (or --define) sets environment declarations that you read with String.fromEnvironment, int.fromEnvironment and bool.fromEnvironment. They are compile-time constants, so they're baked into the executable. This is the usual way to embed a version number or a build flavor:

dart compile exe bin/greet.dart -o build/greet -DAPP_VERSION=1.4.0
./build/greet --version
greet 1.4.0

Several defines can be given:

dart compile exe bin/server.dart -o build/server \
  -DAPP_VERSION=1.4.0 -DFLAVOR=prod -DMAX_WORKERS=8
const flavor = String.fromEnvironment('FLAVOR', defaultValue: 'dev');
const maxWorkers = int.fromEnvironment('MAX_WORKERS', defaultValue: 2);
const isProd = flavor == 'prod';

void main() {
  if (!isProd) {
    print('debug mode, $maxWorkers workers');
  }
}

Because isProd is a constant, the compiler removes the if body entirely from a prod build.

These values are visible to anyone who runs strings on the binary. Never pass secrets like API keys with -D; read them at runtime from environment variables (Platform.environment) or a config file. See Constants for more on fromEnvironment.

dart run accepts the same flag, so you can test it without compiling:

dart run -DAPP_VERSION=1.4.0 bin/greet.dart --version

Detecting that you run as a compiled program

The Dart runtime defines dart.vm.product as true in AOT-compiled code:

const isAot = bool.fromEnvironment('dart.vm.product');

void main() {
  print(isAot ? 'compiled (AOT)' : 'running in the VM (JIT)');
}

dart run prints running in the VM (JIT), the executable prints compiled (AOT).

Asserts are disabled

assert() statements are not executed in AOT-compiled code (they are also off with plain dart run unless you pass --enable-asserts):

void withdraw(int amount) {
  assert(amount > 0, 'amount must be positive');
  print('withdrawing $amount');
}

void main() => withdraw(-5);
dart run --enable-asserts bin/assert_demo.dart
# Unhandled exception: 'file:///.../assert_demo.dart': Failed assertion: ... amount must be positive

dart compile exe bin/assert_demo.dart -o build/assert_demo
./build/assert_demo
# withdrawing -5

Use asserts for developer checks only. Validation that must always happen should throw an exception. See Exceptions.

Smaller binaries and symbols

-S (--save-debugging-info) strips debugging information out of the executable and saves it in a separate file:

dart compile exe bin/greet.dart -o build/greet -S build/greet.symbols

The executable gets smaller, and stack traces from a crash show only addresses instead of function names. Keep the symbols file for each release (don't ship it), and use it to turn such a stack trace back into readable form:

./build/greet 2> crash.txt
dart pub global activate native_stack_traces
dart pub global run native_stack_traces:decode translate -d build/greet.symbols -i crash.txt

Some other options of dart compile exe:

Option Meaning
-o, --output output file
-D, --define=<key>=<value> compile-time environment declaration
-S, --save-debugging-info=<file> strip debug info into a separate file
--enable-asserts keep assert() checks in the compiled code
--target-os, --target-arch cross-compile (Linux targets only, see below)
-p, --packages use a specific package_config.json
--verbosity=error|warning|info|all how much compiler output to print

Run dart compile exe --help for the full list for your SDK version.

Cross-compiling for Linux

Historically dart compile exe could only produce an executable for the OS and CPU it ran on. Since Dart 3.8 you can cross-compile to Linux from macOS, Windows or Linux:

# build a Linux x64 server binary on a Mac or Windows laptop
dart compile exe bin/server.dart -o build/server-linux-x64 \
  --target-os=linux --target-arch=x64

# Raspberry Pi or ARM cloud instance
dart compile exe bin/server.dart -o build/server-linux-arm64 \
  --target-os=linux --target-arch=arm64

Supported architectures are arm, arm64, riscv64 and x64. The first time you cross-compile, the SDK downloads the matching AOT runtime. Only Linux is supported as a target. To produce macOS and Windows binaries, build on those platforms, for example with a CI matrix (see below).

AOT snapshots

dart compile aot-snapshot produces the same AOT-compiled code, but without the runtime embedded. You run it with dartaotruntime, which ships in the Dart SDK's bin directory:

dart compile aot-snapshot bin/greet.dart -o build/greet.aot
dartaotruntime build/greet.aot Alice
Hello, Alice!
...

This is useful when you ship several programs to the same machine: they share one copy of dartaotruntime instead of each carrying its own runtime. Like exe, an AOT snapshot is tied to one OS and CPU architecture, and it must be run by a dartaotruntime from the same SDK version that compiled it.

JIT snapshots

dart compile jit-snapshot does a training run: it actually runs your program, then saves the VM state together with the code that was already compiled during the run. Starting from the snapshot skips parsing and most compilation:

dart compile jit-snapshot -o build/greet.jit bin/greet.dart Alice
Compiling bin/greet.dart to jit-snapshot file build/greet.jit.
Hello, Alice!
Running on linux (3.9.4)
Executable: /usr/lib/dart/bin/dartvm

Arguments after the source file are passed to the training run, so options like -o must come before it. Make sure the program exits on its own and exercises the code paths you care about. Then run the snapshot with the VM:

dart run build/greet.jit Bob

A JIT snapshot needs the Dart SDK at runtime, but it keeps JIT features such as dart:mirrors and peak performance from runtime optimizations. It is mostly used for large tools that must start quickly on developer machines.

Kernel snapshots

dart compile kernel produces a .dill file: your program and its dependencies in Dart's intermediate representation. It is not machine code, so it works on any OS and CPU that has a compatible Dart SDK:

dart compile kernel bin/greet.dart -o build/greet.dill
dart run build/greet.dill Alice

It starts faster than running from source because parsing and type checking are already done, but it's still JIT-compiled at runtime.

Limitations of AOT-compiled code

AOT compilation needs to know all code at compile time, so some dynamic features are not available in exe and aot-snapshot output:

Locating files next to the executable

A common pattern is to look for configuration or assets relative to the binary. The same code works with dart run during development if you fall back to the project directory:

import 'dart:io';

const isAot = bool.fromEnvironment('dart.vm.product');

Directory appDir() {
  if (isAot) {
    return File(Platform.resolvedExecutable).parent;
  }
  // `dart run` from the project root
  return Directory.current;
}

void main() {
  final config = File('${appDir().path}${Platform.pathSeparator}config.json');
  print('config: ${config.path} exists=${config.existsSync()}');
}

Packages with native code

If a dependency uses native assets (C libraries built or downloaded through package build hooks, for example sqlite3), a single-file executable is not enough: the shared libraries must be shipped next to it. Use dart build cli instead of dart compile exe, which runs the build hooks and creates a bundle directory:

dart build cli

The output directory contains a bundle folder with the executable in bundle/bin/ and the native libraries it needs in bundle/lib/. The executable finds those libraries using relative paths, so keep the layout intact.

Copy the whole bundle directory when deploying. Packages that only use plain dart:ffi to open a system library (DynamicLibrary.open('libfoo.so')) work with dart compile exe, as long as the library is installed on the target machine.

Installing tools with dart pub global

For tools aimed at Dart developers, you don't have to distribute binaries at all. List the executables in pubspec.yaml:

name: greet
executables:
  greet: greet   # command name: file in bin/ without .dart

Users install it with:

dart pub global activate greet           # from pub.dev
dart pub global activate --source path . # from a local checkout
greet Alice

pub precompiles the tool to a snapshot on activation, so it starts reasonably fast, but it still needs the Dart SDK. Compile with dart compile exe when your users are not Dart developers.

Building release binaries in CI

Because native executables are platform-specific, build them on each OS. A GitHub Actions matrix:

name: release
on:
  push:
    tags: ['v*']

jobs:
  build:
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            out: greet-linux-x64
          - os: macos-latest
            out: greet-macos-arm64
          - os: windows-latest
            out: greet-windows-x64.exe
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
      - uses: dart-lang/setup-dart@v1
      - run: dart pub get
      - run: mkdir -p build
        shell: bash
      - run: >
          dart compile exe bin/greet.dart
          -o build/${{ matrix.out }}
          -DAPP_VERSION=${{ github.ref_name }}
      - uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.out }}
          path: build/${{ matrix.out }}

Add a Linux arm64 build to the Ubuntu job with --target-os=linux --target-arch=arm64 instead of a separate runner. See Testing in CI for running tests in the same workflow.

On macOS, a downloaded binary must be code-signed and notarized or Gatekeeper will block it. The executable produced by dart compile exe can be signed with the standard codesign tool.

Deploying a server in a container

A compiled server needs only a minimal runtime image. Compile in a stage with the SDK and copy just the binary into a small image:

FROM dart:stable AS build
WORKDIR /app
COPY pubspec.* ./
RUN dart pub get
COPY . .
RUN dart compile exe bin/server.dart -o bin/server

FROM scratch
COPY --from=build /runtime/ /
COPY --from=build /app/bin/server /app/bin/server
EXPOSE 8080
CMD ["/app/bin/server"]

The official dart image provides a /runtime/ directory with the few system files (C library, CA certificates, timezone data) a compiled Dart program needs, so the final image is built FROM scratch and is only a few megabytes larger than the executable itself.

Summary

Task Command
Native executable dart compile exe bin/app.dart -o build/app
Embed a value dart compile exe ... -DAPP_VERSION=1.0.0
Strip and keep symbols dart compile exe ... -S build/app.symbols
Cross-compile for Linux dart compile exe ... --target-os=linux --target-arch=arm64
AOT snapshot dart compile aot-snapshot ... -o app.aot, run with dartaotruntime app.aot
JIT snapshot dart compile jit-snapshot -o app.jit bin/app.dart <training args>
Portable kernel dart compile kernel ... -o app.dill, run with dart run app.dill
Bundle with native assets dart build cli
Check for AOT at runtime const bool.fromEnvironment('dart.vm.product')

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents