首页 > 解决方案 > 如何使用“dart pub global run”命令运行脚本?

问题描述

我的包目录foo

在此处输入图像描述

pubspec.yaml 文件有:

name: foo

executables:
  foo: bar

foo使用激活包dart pub global activate ...,如果我将目录添加到PATH环境,则以下命令有效:

foo bar

但是如果我删除它并尝试运行该dart pub global run命令,它就不起作用。

me@mac foo % dart pub global run foo bar
Could not find bin/foo.dart.

那么,如何在不将其添加到PATHusing的情况下运行脚本,如此处dart pub global run建议那样。

您可以从命令行直接从激活的包中运行脚本。如果无法直接运行脚本,也可以使用 dart pub global run。

注意dart pub global run foo:bar有效,但这与文件中定义的可执行文件无关pubspec.yaml

标签: dartcommand-line

解决方案


指定:

executables:
  foo: bar

意味着当包被激活时,该命令foo将映射到文件bar.dart. bar调用时无需指定。

例如,我有这个包:

name: dictionary
...
executables:
    scrabble:

它定义了一个scrabble调用scrabble.dart. 我这样激活它:

dart pub global activate --source path dictionary

这报告:

...
Installed executable scrabble.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

我可以调用scrabble调用scrabble.dart. 我也可以这样调用它:

dart pub global run dictionary:scrabble

如果我pubspec有:

executables:
    dictionary: scrabble

然后该命令dictionary调用文件scrabble.dart

(不要忘记pub在您的PATH.C:\Users\pohara\AppData\Roaming\Pub\Cache\bin

补充:继续这个dictionary: scrabble例子,当我激活字典时,我得到:

...
Installed executable dictionary.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

pub在 Windows 上的缓存有这个文件来运行dictionary命令:

> cat C:\Users\pohara\AppData\Roaming\Pub\Cache\bin\dictionary.bat
@echo off
rem This file was created by pub v2.12.2.
rem Package: dictionary
rem Version: 1.0.0
rem Executable: dictionary
rem Script: scrabble
pub global run dictionary:scrabble %*

因此该命令dictionary显式运行包scrabble中的文件dictionary

这两个命令都失败了:

> dart pub global run dictionary scrabble
Could not find bin\dictionary.dart.

> dart pub global run dictionary
Could not find bin\dictionary.dart.

当然,这个成功了:

> dart pub global run dictionary:scrabble

这与文档https://dart.dev/tools/pub/pubspec#executables一致。


推荐阅读