使用 pub global activate

时间:2021-05-29 10:57:56

标签: dart dart-pub

我创建了一个新的 Dart 应用,如下所示:

dart create hello

我可以像这样运行应用程序:

dart run hello/bin/hello.dart

我尝试像这样激活应用程序:

dart pub global activate --source path hello

但我无法像预期的那样运行该文件:

hello
<块引用>

zsh:找不到命令:你好

.pub-cache/bin 文件夹在我的缓存中,但 pub global activate 没有把它放在那里。

这确实有效:

dart pub global run hello
<块引用>

世界,你好!

但我希望无需每次都输入 dart pub global run 即可运行脚本。

如果我从 pub.dev 做一个包,它工作正常:

dart pub global activate webdev

它在 .pub-cache/bin 文件夹中放置了一个 webdev 可执行文件,我可以运行它。

webdev --version
<块引用>

2.7.4

那么我还需要执行其他步骤来让我的 hello 应用程序进入可执行文件夹吗?

我也尝试编译它:

dart compile exe hello/bin/hello.dart

并再次激活它:

dart pub global activate --source path hello

但是 .pub-cache/bin 文件夹中仍然没有二进制文件。有什么建议吗?

更新

在得到下面凯文的回答后,我在 pubspec.yaml 中添加了以下内容:

executables:
  hello:

然后我运行了以下命令:

dart pub global activate --source path hello

结果如下(用户名已修改):

Resolving dependencies... 
Got dependencies!
Package hello is currently active at path "/Users/suragch/Dev/DartProjects/hello".
Installed executable hello.
Activated hello 1.0.0 at path "/Users/suragch/Dev/DartProjects/hello".

但是如果我运行这个:

hello

我收到以下错误:

/Users/suragch/.pub-cache/bin/hello: line 7: pub: command not found

运行这个仍然有效:

dart pub global run hello
<块引用>

世界,你好!

2 个答案:

答案 0 :(得分:1)

您需要在 bin/ 文件的 executables 部分中列出 pubspec.yaml 下要执行的文件。例如,要使 bin/hello.dart 可执行,请将以下内容添加到 pubspec.yaml

....
executables:
  hello:

....

然后当你运行时:dart pub global activate --source path hello

您现在可以在 hello 中调用 bin/ 而无需运行:pub global run hello

再来

您必须在 CLI 中 executables 中的 pubspec.yaml 键下列出您打算提供给您的软件包用户的每个可执行文件

答案 1 :(得分:0)

所以看起来这个问题是由于从pub切换到dart pub导致的错误引起的。如果您使用编辑器打开 .pub-cache/bin/hello 文件,您将看到以下内容:

#!/usr/bin/env sh
# This file was created by pub v2.13.1.
# Package: hello
# Version: 1.0.0
# Executable: hello
# Script: hello
pub global run hello:hello "$@"

关于第 7 行的错误是您可以看到它引用普通 pub 的最后一行。将该行更改为以下内容:

dart pub global run hello:hello "$@"

现在您可以从任何地方运行您的应用:

hello
<块引用>

世界,你好!

这只是一个临时的解决方法。关注 this issue 获取更新。感谢 Kelvin Omereshone 为我指明了正确的方向。