jinyus
jinyus

Reputation: 566

Run dart script outside of a project folder

I am trying to replace python with dart as a scripting language for my tools. I can create a python file anywhere, import global packages and run it but I can't seem to get this working with dart. Do I always need a pubspec.yaml file to run a dart script?

This is the script I am trying to run:

import 'package:http/http.dart' as http;

main(List<String> args) async{
  var res = await http.get('https://example.com');
  print(res.headers);
}

This is the error I am getting:

Error: Could not resolve the package 'http' in 'package:http/http.dart'.
test2.dart:1:8: Error: Not found: 'package:http/http.dart'
import 'package:http/http.dart' as http;
       ^
test2.dart:4:19: Error: Method not found: 'get'.
  var res = await http.get('https://example.com');

Upvotes: 1

Views: 829

Answers (1)

Hoylen
Hoylen

Reputation: 16990

No, you don't need a pubspec.yaml file to run a program, but it does need to somehow be able to resolve all the imports.

The pubspec.yaml file is used for obtaining the packages (from pub.dev, a git repository, etc.) but not for finding the packages at runtime. The pub program reads the pubspec.yaml file and downloads the packages mentioned in it, and maintains a packages specification file indicating where each package resolves to. By default the packages specification is in a file called .packages in the same directory as the pubspec.yaml file. The Dart runtime normally finds the packages by looking at the .packages package specification file, but there are other ways.

Here are some options:

  1. Put a .packages file in the same directory as the Dart program, or in an ancestor directory.

  2. Use the --packages option to specify the package specification file to use:

    dart --packages=/home/username/stuff/mypackagespecfile  myprogram.dart
    
  3. The Dart runtime also has a --package-root option. But I haven't figured out how to make it work.

  4. The import statements use URIs, so import 'file://...'; can also work in some cases.

  5. Use dart2native to compile the program into an executable.


Note: Dart scripts can also start with a hash-bang line:

#!/usr/bin/env dart

import 'package:http/http.dart' as http;

main(List<String> args) async{
  var res = await http.get('https://example.com');
  print(res.headers);
}

Then you can make the program executable and run it without needing to type in the Dart runtime:

$ chmod a+x myprogram.dart
$ ./myprogram.dart

Upvotes: 5

Related Questions