Deno CLI
什麼是 Deno CLI ?
Deno 是一個命令列介面的應用程式,它提供了一些指令可供使用。
使用方式
查詢指令的說明
deno help
deno -h
# 該命令會輸出更多細節資訊
deno --help
運行檔案、腳本
# 本地檔案
deno run app.ts
# 線上檔案
deno run https://deno.land/std@0.160.0/examples/welcome.ts
傳送參數至檔案、腳本
deno run app.ts a b -c --quiet
可以透過 Deno.args
獲取參數。
app.ts
console.log(Deno.args); // ['a', 'b', '-c', '--quiet']
Danger
如果要同時使用 flag 的話,像是開啟存取網路權限,需在檔案、腳本名稱前方添加 flag, 否則會被 Deno 認為是參數並傳入至檔案、腳本中。
監聽檔案、程式
deno run --watch app.ts
快取、確保相依套件完整、一致性
deno cache --lock=lock.json --lock-write src/deps.ts
lock.json
{
"https://deno.land/std@0.71.0/textproto/mod.ts": "3118d7a42c03c242c5a49c2ad91c8396110e14acca1324e7aaefd31a999b71a4",
"https://deno.land/std@0.71.0/io/util.ts": "ae133d310a0fdcf298cea7bc09a599c49acb616d34e148e263bcb02976f80dee",
"https://deno.land/std@0.71.0/async/delay.ts": "35957d585a6e3dd87706858fb1d6b551cb278271b03f52c5a2cb70e65e00c26a",
...
}
使用 flag 允許相關權限
-A
,--allow-all
允許所有權限--allow-env
允許環境訪問--allow-hrtime
允許高精度的時間測量--allow-net
允許網路存取--allow-plugin
允許加載插件,需額外使用--unstable
--allow-read
允許程式碼對檔案進行讀取--allow-run
允許運行子進程--allow-write
允許程式碼對檔案進行寫入
deno run --allow-net app.ts
檢查依賴模組
deno info https://deno.land/std@0.67.0/http/file_server.ts
也可以用來查看本地快取資訊
deno info
產生文件
deno doc app.ts
如果要輸出為 JSON 格式可以使用 --json
flag。
打包程式碼
deno bundle https://deno.land/std@0.73.0/examples/colors.ts colors.bundle.js
程式碼格式化
deno fmt
單元測試
若是要進行測試的話,需先引用 Deno 標準庫內的斷言模組。
app.test.ts
import { assert } from 'https://deno.land/std@0.73.0/testing/asserts.ts'
Deno.test('hello, test', () => {
assert('hello');
});
接著透過終端機輸入以下指令開始測試:
deno test app.test.ts
Deno 一共提供了 10 種斷言方法:
assert
assertEquals
assertNotEquals
assertStrictEquals
assertStringContains
assertArrayContains
assertMatch
assertNotMatch
assertThrows
assertThrowsAsync
使用 Denon 精簡指令
安裝
deno install -qAf --unstable https://deno.land/x/denon/denon.ts
使用方式
使用下方指令生成 Denon 配置:
denon --init
## 使用 TypeScript 設定配置
denon --init typescript
基本配置為
scripts.json
{
// optional but highly recommended
"$schema": "https://deno.land/x/denon/schema.json",
"scripts": {
"start": {
"cmd": "deno run app.ts",
"desc": "run my app.ts file"
}
}
}
更多可用的配置、設定可以至 Denon 查看。