前言
如果你接触过npm/yarn 应该知道,有一些包可以全局使用,就是安装后可以直接用,比如vue-cli这样的应用,应该是用node开发的
在dart中也可以实现类似的功能, 使用pub global就可以了,在连接中有完整的说明
也有stagehand这样的应用程序可以直接使用
我在这里简单的实战一下,实现一个简单的cli应用程序
这个程序没什么多余的功能,就简单的实现输入敲击unix
获取时间戳
建立工程前的准备
将dart,pub加入PATH环境变量
需要在环境变量中添加几个东西,添加环境变量的方式自己搜索一下
一个是dart/bin的目录,你需要在命令行中让dart命令可用
➜ ~ dart --version
Dart VM version: 2.1.0 (Tue Nov 13 18:22:02 2018 +0100) on "macos_x64"
相对应的dart/bin目录下还会有其他的一些工具,包含了pub,这个工具也是会用到的
➜ bin pub --version
Pub 2.1.0
安装dart工程脚手架
$ pub global activate stagehand
将pub-cache/bin目录加入PATH环境变量
这个目录通常是~/.pub-cache/bin
目录
验证stagehand
可用
➜ bin stagehand
Stagehand will generate the given application type into the current directory.
usage: stagehand <generator-name>
--[no-]analytics Opt out of anonymous usage and crash reporting.
-h, --help Help!
--version Display the version for stagehand.
--author The author name to use for file headers.
(defaults to "<your name>")
Available generators:
console-full - A command-line application sample.
package-simple - A starting point for Dart libraries or applications.
server-shelf - A web server built using the shelf package.
web-angular - A web app with material design components.
web-simple - A web app that uses only core Dart libraries.
web-stagexl - A starting point for 2D animation and games.
建立工程
这一步默认你所有的环境变量都配置完毕,dart pub stagehand 都可用
mkdir -p /tmp/dart/unix
cd /tmp/dart/unix
stagehand console-full
pub get
code .
我这里使用vscode
打开
文件夹结构是这样的
修改两个unix文件
bin/unix.dart
import 'package:unix/unix.dart' as unix;
main(List<String> arguments) {
print(unix.getUnixTimeString());
}
lib/unix.dart
String getUnixTimeString() {
return DateTime.now().millisecondsSinceEpoch.toString();
}
执行
dart bin/unix.dart
➜ unix dart bin/unix.dart
1551074662254
这样一个简单的应用程序就开发完了
本地安装
参考官方连接
pub global activate --source path /tmp/dart/unix
➜ unix pub global activate --source path /tmp/dart/unix
Resolving dependencies...
Got dependencies!
Activated unix 0.0.0 at path "/private/tmp/dart/unix".
运行脚本
➜ .pub-cache pub global run unix
1551076677872
这样就可以运行名为unix
的脚本
生成应用程序
修改pubspec.yaml
在结尾处添加如下代码
executables:
unix:
然后在命令行输入
➜ unix pub global activate --source path /tmp/dart/unix
Resolving dependencies...
Got dependencies!
Package unix is currently active at path "/private/tmp/dart/unix".
Installed executable unix.
Activated unix 0.0.0 at path "/private/tmp/dart/unix".
出现 Installed executable unix.
字样,说明可执行文件ok了
再次输入unix
➜ unix
1551077074760
这样unix这个程序就可以直接运行了
上传应用包
开发完了这个简单的应用包,我们既可以上传到pub了
我们直接使用命令上传应用包,这一步需要保证终端可以科学上网
pub publish --server https://pub.dartlang.org
使用
➜ pub global activate unix
Package unix is currently active at path "/private/tmp/dart/unix".
Resolving dependencies... (3.5s)
+ unix 1.0.0
Downloading unix 1.0.0...
Precompiling executables...
Precompiled unix:unix.
Installed executable unix.
Activated unix 1.0.0.
这样就代表我从官网获取到了unix这个应用程序
➜ unix
1551078268562
可以用,说明成功了
后记
对于flutter开发者来说,这个方案可以创建一些自己的应用包,然后可以使用dart语言来做一些快捷的脚本,毕竟dart语言会比较熟悉