DEV Community

Cover image for Dart Library and CLI Project
Mathieu K
Mathieu K

Posted on

Dart Library and CLI Project

Creating a library is great, in particular if one wants to avoid doing duplicated code, but the library can also be released with a command line interface for simple tasks (or tests).

A Dart package (or library) can be created using dart create command, the --template flag define which kind of skeleton will be used for the project, in this case, it will be a package project.

dart create --template package mycli
Enter fullscreen mode Exit fullscreen mode

The tree generated is straightforward and contains only the required files to do a successful build.

$ tree
.
├── analysis_options.yaml
├── CHANGELOG.md
├── example
│   └── mycli_example.dart
├── lib
│   ├── mycli.dart
│   └── src
│       └── mycli_base.dart
├── pubspec.lock
├── pubspec.yaml
├── README.md
└── test
    └── mycli_test.dart

5 directories, 9 files
Enter fullscreen mode Exit fullscreen mode

Let try to run the code with dart run.

$ dart run
Resolving dependencies in `/home/user/tmp/dart/mycli`... 
Downloading packages... 
Got dependencies in `/home/user/tmp/dart/mycli`.
Could not find `bin/mycli.dart` in package `mycli`.
Enter fullscreen mode Exit fullscreen mode

It fails. Why? Because no executables entry-points have been defined somewhere. Let creates ./bin/main.dart file, simply containing a main() function.

mkdir bin
cat > bin/mycli.dart << EOF
void main() {
  print("hello");
}
EOF
Enter fullscreen mode Exit fullscreen mode

Now, we can try to run it. It should not fail.

$ dart run
hello
Enter fullscreen mode Exit fullscreen mode

It works! If you want to define custom command line application, a list of executables can be defined in pubspec.yaml.


Image Cover by Clem Onojeghuo on Unsplash

Top comments (0)